首页>itarticle>3. longest substring without repeating characters 实现 参考资料
3. longest substring without repeating characters 实现 参考资料
admin11月 14, 20200
Given a string, find the length of the longest substring without repeating characters.
Example 1:
1 2 3
Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3.
Example 2:
1 2 3
Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1.
Example 3:
1 2 3 4
Input: "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
if (s == null || s.length() == 0){ return0; } int max = 0; int temp = 0; int len = s.length(); char[] ary = s.toCharArray(); Set<Character> res = new HashSet<>(); for (int i = 0; i < len; i++){ char out = ary[i]; if (!res.contains(out)){ temp++; res.add(out); for (int j = i+1; j < len;j++){ char in = ary[j]; if (!res.contains(in)){ temp ++; res.add(in); } else { break; } } if (temp > max){ max = temp; } temp = 0; res.clear(); } else { break; } } return max;
讨论区其他答案
java
HashMap求解
1 2 3 4 5 6 7 8 9 10 11 12 13
publicint(String s){ if (s.length()==0) return0; HashMap<Character, Integer> map = new HashMap<Character, Integer>(); int max=0; for (int i=0, j=0; i<s.length(); ++i){ if (map.containsKey(s.charAt(i))){ j = Math.max(j,map.get(s.charAt(i))+1); } map.put(s.charAt(i),i); max = Math.max(max,i-j+1); } return max; }
近期评论