給定一個字符串,找到最長子串的長度,而不重複字符。函數
給定"abcabcbb"
的答案是"abc"
,長度是3。spa
給定"bbbbb"
的答案是"b"
,長度爲1。code
給定"pwwkew"
的答案是"wke"
,長度爲3.請注意,答案必須是子字符串,"pwke"
是子序列,而不是子字符串。blog
public static int lengthOfLongestSubstring(String s) { int start, end; String count = ""; String str = ""; for(start=0; start<s.length(); start++){ for(end=start+1; end<=s.length(); end++){ str = s.substring(start, end); if(end == s.length()){ if(count.length() < str.length()){//對比長度 count = str; } break; }else{ if(str.contains(s.substring(end, end+1))){//當有重複時候,處理,跳出循環讓start++ if(count.length() < str.length()){//對比長度 count = str; } break; } } } } return count.length(); }
一、假設有一個函數allUnique(),能檢測某字符串的子串中的全部字符都是惟一的(無重複字符),那麼就能夠實現題意描述:ip
public class Solution { public int lengthOfLongestSubstring(String s) { int n = s.length(); int ans = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j <= n; j++) if (allUnique(s, i, j)) ans = Math.max(ans, j - i); return ans; } public boolean allUnique(String s, int start, int end) { Set<Character> set = new HashSet<>(); for (int i = start; i < end; i++) { Character ch = s.charAt(i); if (set.contains(ch)) return false; set.add(ch); } return true; } }
二、滑動窗口思想:若是肯定子串s[i,j](假設表示字符串的第i個字符到第j-1個字符表示的子串),那麼只須要比較s[j]是否與子串s[i,j]重複便可rem
若重複:記錄此時滑動窗口大小,並與最大滑動窗口比較,賦值。而後滑動窗口大小重定義爲1,頭位置不變,並右移一個單位。字符串
若不重複:滑動窗口頭不變,結尾+1,整個窗口加大1個單位。繼續比較下一個。get
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; } }
三、使用HashMapstring
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; } }
四、io
public class Solution { public int lengthOfLongestSubstring(String s) { int n = s.length(), ans = 0; int[] index = new int[128]; // current index of character // try to extend the range [i, j] for (int j = 0, i = 0; j < n; j++) { i = Math.max(index[s.charAt(j)], i); ans = Math.max(ans, j - i + 1); index[s.charAt(j)] = j + 1; } return ans; } }