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.
Solution: O(n) space+O(n) time
public class Solution { public int lengthOfLongestSubstring(String s) { if(s == null || s.length() == 0) return 0; if(s.length() == 1) return 1; char set[] = s.toCharArray(); HashMapmap = new HashMap (); int cur = 0; int max = 1; map.put(""+set[0], 0); for(int i=1; i< set.length;i++){ String key = ""+set[i]; if(map.get(key) == null){ map.put(key, i); }else{ int p = map.get(key); cur = Math.max(p+1, cur); map.put(key,i); } max = Math.max(max, i-cur+1); } return max; } }
Notice:
ArrayUtils are not allowed,otherwise we can use Character 1. Because
Character[] set = ArrayUtils.toObject(s.toCharArray());
2. cur = Math.max(p+1, cur); is very important
沒有留言:
張貼留言