Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1. java
https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/ 數組
思路:利用一個exist數組保存字符是否出現(假設char set是ascii),從前向後遍歷數組,若是遇到已存在的字符,應該回退到這個字符上次出現的下一個位置重新開始統計(以下圖),同時注意exist數組的同步更新。 .net
public class Solution { public int lengthOfLongestSubstring(String s) { if (s == null || s.length() == 0) return 0; int res = 1; boolean[] exist = new boolean[256]; int start = 0; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (exist[ch]) { res = Math.max(res, i - start); for (int k = start; k < i; k++) { if (s.charAt(k) == ch) { start = k + 1; break; } exist[s.charAt(k)] = false; } } else exist[ch] = true; } res = Math.max(res, s.length() - start); return res; } public static void main(String[] args) { System.out.println(new Solution().lengthOfLongestSubstring("abcabcbb")); System.out.println(new Solution().lengthOfLongestSubstring("bbbbb")); System.out.println(new Solution() .lengthOfLongestSubstring("fpdcztbudxfipowpnamsrfgexjlbjrfoglthewbhtiriznzmolehqnlpwxrfowwwjrd")); } }
參考: code
http://blog.csdn.net/likecool21/article/details/10858799 blog
http://www.programcreek.com/2013/02/leetcode-longest-substring-without-repeating-characters-java/ ip