题目描述
Given a string s
, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Constraints:
0 <= s.length <= 5 * 104
s
consists of English letters, digits, symbols and spaces.
解题思路
【C++解法】
1. int*
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.length();
int *index = new int[256];
int maxLen = 0, i = 0, j = 0;
for (int j = 0, i = 0; j < n; j++) {
i = max(index[s[j]],i);
maxLen = max(maxLen, j - i + 1);
index[s[j]] = j + 1; // must +1 (j = 0)
}
delete []index;
return maxLen;
}
};
2. vector
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (!s.length()) return 0;
vector<int> index(256, 0);
int maxLen = 0;
for (int j = 0, i = 0; j < s.length(); j++) {
i = max(index[s[j]], i);
maxLen = max(maxLen, j - i + 1);
index[s[j]] = j + 1;
}
return maxLen;
}
};
3. unordered_map
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.length(), maxlen = 0;
unordered_map<char,int> subStrMap;
for(int i=0, j=0; j<n; j++) {
if(subStrMap.count(s[j])) i = max(subStrMap[s[j]],i);
maxlen = max(maxlen,j-i+1);
subStrMap[s[j]] = j+1;
}
return maxlen;
}
};
【Java解法】
1. int[]
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.length() <= 0) {return 0;}
int[] index = new int[256];
int maxLen = 0;
char[] ss = s.toCharArray();
for (int step=0, j=0; j<s.length(); j++) {
step = Math.max(step, index[ss[j]]);
maxLen = Math.max(maxLen, j - step + 1);
index[ss[j]] = j + 1;
}
return maxLen;
}
}
2. Map
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.length() == 0) return 0;
Map<Character, Integer> map = new HashMap<>();
int maxLen = 0;
for (int j = 0, i = 0; j < s.length(); j++) {
if (map.containsKey(s.charAt(j))) i = Math.max(map.get(s.charAt(j)), i);
maxLen = Math.max(maxLen, j - i + 1);
map.put(s.charAt(j), j + 1);
}
return maxLen;
}
}