您的位置:首页 > 其它

【leetcode】3. Longest Substring Without Repeating Characters

2016-04-10 11:36 447 查看
计算最长的无重复字符的串长

用HashMap记住重复的单词及其位置。当重复时,让tempStart指针移到重复位置+1,如果start指针小于tempStart,则更新start指针,长度就是当前重复的位置 - start。读到字符串末尾时还需要判断一次

public class Solution {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> map = new HashMap<Character, Integer>();
int start = 0;
int maxLength = 0;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (map.containsKey(c)) {
int length = i - start;
int tempStart = map.get(c) + 1;
start = start > tempStart ? start : tempStart;
if (maxLength < length) {
maxLength = length;
}
}
map.put(c, i);
}
int length = s.length() - start;
if (maxLength < length) {
maxLength = length;
}
return maxLength;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: