3. Longest Substring Without Repeating Characters

来源:互联网 发布:字幕重叠拼图软件 编辑:程序博客网 时间:2024/06/15 06:54

原题地址

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 subsequence and not a substring.


一开始的思路:逐位扫描,将每位的字符与下标存到HashMap中,遇到重复字符时,计算map长度,从map中取出重复字符前一次出现时的下标,同时清空map。

从取出的下标的下一位开始重复上一过程。

当余下的字符串长度目前小于已知的最大长度时就不必再往后扫描了。

代码如下:

public class Solution {public int lengthOfLongestSubstring(String s) {HashMap<Character, Integer> map = new HashMap<Character, Integer>();int longest = 0;if(s != null){for(int i = 0; i < s.length(); i++){char c = s.charAt(i);if(!map.containsKey(c)){map.put(c,i);if(map.size() > longest){longest = map.size();}}else{if(map.size() > longest){longest = map.size();}i = map.get(c);if(s.length()-1-i <= longest){break;}map.clear();}}}return longest;}}


该方案提交时在遇到字符串长度很长时会出现运行时间过长,原因在于每次遇到重复值时都需要重新构建map。



参考其他人的方案后使用新的思路:

不再清空map重构,记录当前子串开始时的下标,遇到重复字符时就更新map中重复字符的下标值。

如果重复的字符是在当前子串开始位置之前的,则只更新map就行,否则说明当前子串中出现了重复的字符,需要同时更新子串开始下标。

子串的长度就是当前下标与开始下标的差值+1.

此方案Accepted,代码如下:

public class Solution {public int lengthOfLongestSubstring(String s) {HashMap<Character, Integer> map = new HashMap<Character, Integer>();int longest = 0;if(s != null){for(int i = 0, start = i; i < s.length(); i++){char c = s.charAt(i);if(map.containsKey(c)){start = Math.max(start, map.get(c)+1);}map.put(c,i);longest = Math.max(longest, i-start+1);}}return longest;}}


0 0
原创粉丝点击