标签:leetcode
https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/
http://fisherlei.blogspot.com/2012/12/leetcode-longest-substring-without.html
public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null || s.isEmpty())
return 0; // invalid input
// A map of [char, position]
Map<Character, Integer> map = new HashMap<>();
char[] chars = s.toCharArray();
int len = chars.length;
int start = 0;
int end = 0;
int maxLen = -1;
for (; end < len ; end ++)
{
char c = chars[end];
Integer lastPos = map.get(c);
if (lastPos == null)
{
map.put(c, end);
int curLen = end - start + 1;
if (curLen > maxLen)
maxLen = curLen;
}
else
{
// Clear all chars <= lastPos, including c.
// Then update c with end.
// reset start = lastPos + 1;
for (int i = start ; i <= lastPos ; i ++)
{
map.remove(chars[i]);
}
start = lastPos + 1;
map.put(c, end);
}
}
if (maxLen == -1) // All chars are the same. return 1.
return 1;
return maxLen;
}
}[LeetCode]3 Longest Substring Without Repeating Characters
标签:leetcode
原文地址:http://7371901.blog.51cto.com/7361901/1598391