LeetCode之3:Longest Substring Without Repeating
问题描述:
查找一个字符串的最长不重复子序列。
问题的陷阱与难点:
- 能否在O(N)时间内完成搜索。
- 能否在较短时间内理清逻辑,快速写出代码。
缺陷代码分析(优于51.30% 在线提交)
import java.util.*;
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s==null || s.length()==0)
return 0;
Map<Character, Character> map = new HashMap<>();//用一个HashMap存放当前不重复的字符
int length = s.length();
int max = 0;//保存最大不重复子序列的长度
int curLengh = 0;//保存当前子序列的长度
char[] array = s.toCharArray();
int left, right;//当前子序列的左右边界
left = right = 0;
while (right < length) {
if (map.get(array[right])==null) {//如果当前字符唯一,则子序列向右扩展,并更新curLength值。
map.put(array[right],array[right]);//保存这个当前字符
curLengh++;
max = max < curLengh ? curLengh : max;//更新max值
} else {
//如果字符重复,则删掉子序列中左边界到重复字符的所有字符
//调整left和curLength值。因为保留重复字符左侧的任何字符对于获取更长的子序列都是无意义的。
max = max < curLengh ? curLengh : max;//如果当前子序列是最长的,则更新max
while(array[left]!=array[right]) {//删除操作
map.remove(array[left]);
left++;
curLengh--;
}
left++;
}
right++;//继续遍历
}
return max;
}
}
这道题主要考察的是思路,即如何在碰到重复字符后,通过尽可能少的遍历操作定位下一个长串。我的主要思路是删除当前子序列中左边界到重复字符的所有字符,因为保留重复字符左侧的任何字符对于获取更长的子序列都是无意义的。(子序列动起来有点像一条蠕动的蚯蚓,你们脑补一下)
- 使用HashMap保存唯一字符是否是合理的?