๋ฌธ์ :
https://leetcode.com/problems/longest-substring-without-repeating-characters/
๋์ด๋ : Medium
ํ์ด ๋ฐฉ๋ฒ : ๋ธ๋ฃจํธ ํฌ์ค O(n^2)
๋ฌธ์์ด s์์ ์ค๋ณต๋๋ ๋ฌธ์ ์์ด ๊ฐ์ฅ ๊ธด ์๋ธ ์คํธ๋ง์ ์ฐพ๋ ๋ฌธ์ ์๋ค.
์ฌ๋ผ์ด๋ฉ ์๋์ฐ ๋ฐฉ์์ ์ฌ์ฉํ๋ฉด O(n) ๋งํผ์ผ๋ก๋ ํด๊ฒฐ ํ ์ ์๋ค๊ณ ํ๋ค. ๋ฆฌํธ์ฝ๋์ ํ ํฝ ๋ณด๋ ๋ฐฉ๋ฒ์ ๋ชฐ๋ผ ํ๋ฆฌ๋ ๋๋ก ํ์๋๋ฐ ์ด์ ๋ ์ข ํจ์จ์ ์ ํธ๋ ๋ฐฉ๋ฒ๋ ๊ฐ์ด ๊ณต๋ถํด์ผ๊ฒ ๋ค ํํ
c++ ์ฝ๋ (๋ธ๋ฃจํธํฌ์ค)
class Solution {
public:
string answer = "";
int answerLength = 0;
int lengthOfLongestSubstring(string s) {
if(s.length() == 1){
return 1;
}
for(int i = 0; i< s.length(); i++){
for(int j = i; j < s.length(); j ++){
char findCharacter = s[j];
if(answer.find(findCharacter) == -1){ // can not find
answer += findCharacter;
}else {
if(answerLength < answer.length()){
answerLength = answer.length();
}
answer = "";
break;
}
}
}
return answerLength;
}
};
c++ ์ฌ๋ผ์ด๋ฉ ์๋์ฐ ๋ฐฉ์
: ํ์ด๋ณผ ์์
class Solution {
public:
int lengthOfLongestSubstring(string s) {
//SLIDING WINDOW - TIME COMPLEXITY O(2n)
// SPACE COMPLEXITY O(m) //size of array
int store[256]={0}; //array to store the occurences of all the characters
int l=0; //left pointer
int r=0; //right pointer
int ans=0; //initializing the required length as 0
while(r<s.length()) //iterate over the string till the right pointer reaches the end of the string
{
store[s[r]]++; //increment the count of the character present in the right pointer
while(store[s[r]]>1) //if the occurence become more than 1 means the char is repeated
{
store[s[l]]--; //reduce the occurence of temp as it might be present ahead also in the string
l++; //contraction of the present window till the occurence of the 't' char becomes 1
}
ans = max(ans,r-l+1); //As the index starts from 0 , ans will be (right pointer-left pointer + 1)
r++; // now will increment the right pointer
}
return ans;
}
};
'Algorithm๐ฐ > ๋ฆฌํธ์ฝ๋' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฆฌํธ์ฝ๋] 238. Product of Array Except Self (0) | 2021.12.10 |
---|---|
[๋ฆฌํธ์ฝ๋] 98. Validate Binary Search Tree - BT (0) | 2021.08.17 |
[๋ฆฌํธ์ฝ๋] 76. Minimum Window Substring (์ฌ๋ผ์ด๋ฉ ์๋์ฐ) (0) | 2021.08.05 |
[๋ฆฌํธ์ฝ๋] 1. Two Sum (๋์์ ํฉ) (0) | 2021.07.12 |
๋๊ธ