我的代码一开始没有考虑字符串为空的特殊情况
public class Test {
public static int lengthOfLongestSubstring(String s) {
int longest=0; //latest char index+1
byte[] b = s.getBytes();
int l = b.length;
byte[] temp = new byte[l];
for (int i = 0; i < l; i++) {
temp[0]= b[i]; //start char
int end=1;
for (int j=i+1;j<l;j++) {
//check b[j] is exist in temp[]
boolean isExist=false;
for (int k=0;k<end;k++) {
if (temp[k] == b[j]) {
isExist=true;
}
}
if (isExist == false) {
temp[end] = b[j];
end++;
} else {
break;
}
}
longest=(longest>end)?longest:end;
if (longest>l-i-1) {
break;
}
}
return longest;
}
public static void main(String[] args) {
String s1 = "bbbbb";
String s2 = "abcabcbb";
String s3 = "pwwkew";
int r1 = lengthOfLongestSubstring(s1);
int r2 = lengthOfLongestSubstring(s2);
int r3 = lengthOfLongestSubstring(s3);
System.out.println("r1 = " + r1);
System.out.println("r2 = " + r2);
System.out.println("r3 = " + r3);
}
}
官方答案2:窗口机制,运用了hashSet,速度加快;
public static int lengthOfLongestSubstring2(String s) {
int l = s.length();
HashSet<Character> set = new HashSet<>();
int ans = 0, i = 0, j = 0;
while (i < l && j < l) {
if (!set.contains(s.charAt(j))) {
set.add(s.charAt(j++));
int t = j - i;
ans = (ans > t) ? ans : t;
} else {
set.remove(s.charAt(i++));
}
}
return ans;
}
官方答案3:两个字,厉害
public class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length(), ans = 0;
Map<Character, Integer> map = new HashMap<>(); // current index of character
// try to extend the range [i, j]
for (int j = 0, i = 0; j < n; j++) {
if (map.containsKey(s.charAt(j))) {
i = Math.max(map.get(s.charAt(j)), i);
}
ans = Math.max(ans, j - i + 1);
map.put(s.charAt(j), j + 1);
}
return ans;
}
}