My Solution:
主要思路:now指针不断后移,每移动一个就与前面的字母比较是否有相同,若有相同,比较当前substring长度是否大于max,记此时相同的位置后一个位置为front,now继续后移...
class Solution {
public int lengthOfLongestSubstring(String s) {
int front = 0;
int now = 1;
int max = 0;
if(s.length()==1)
return 1;
while(now<s.length()){
int i;
for(i = front; i < now; i++){
if(s.charAt(i)==s.charAt(now)){
max = max > now - front? max : now - front;
front = i+1;
break;
}
}
if(i==now){
now++;
if(now==s.length())
max = max > now - front? max : now - front;
}
}
return max;
}
}
Solution:
Approach:Sliding Window
Time Complexity: O(n)
Space Complexity: O(min(m, n))
public class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
Set<Character> set = new HashSet<>();
int ans = 0, i = 0, j = 0;
while (i < n && j < n) {
// try to extend the range [i, j]
if (!set.contains(s.charAt(j))){
set.add(s.charAt(j++));
ans = Math.max(ans, j - i);
}
else {
set.remove(s.charAt(i++));
}
}
return ans;
}
}
对比所得:
1. 思路是差不多的,但使用set明显更易理解。
2.擅用set