题目描述
Given a string, find the length of the longest substring without repeating characters.
样例
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequenceand not a substring.
思路分析
求最长子字符串的长度,方法一是自己写的,很奇怪,O(n2)就已经超时了,,n,方法二是看讨论区的,hashmap解法,O(n)
基本思路:遍历字符串,遇到相同字符即停止,统计长度,大于max则赋值
代码
方法一
public int lengthOfLongestSubstring(String s) { StringBuffer str = new StringBuffer(); int max = 0; for (int i=0; i<s.length(); i++) { for (int j=i; j<s.length(); i++) { if (!str.toString().contains("s.charAt(j)")) { str.append(s.charAt(j)); } else { max = Math.max(max, str.length()); } } } return max; }
方法二
public int lengthOfLongestSubstring(String s) { if (s.length()==0) return 0; 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; }