LeetCode OJ算法题(三):Longest Substring Without Repeating Characters

来源:互联网 发布:java math.ceil 编辑:程序博客网 时间:2024/06/03 15:42

题目:

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.

解法:

看着挺简单一题,做着想SHI的心都有了,一开始采用HashSet,误以为遍历到之前出现过的元素时就清空set继续遍历,结果却发现bmhcdh...这样的序列,遍历到第二个h后应该从cdh...开始,而不是简单的从h开始。

于是改用HashMap,这样就可以知道出现重复时,应该先清空map,从重复元素第一次出现的下一个字符开始遍历,也就是第一个h后的c开始,这样逻辑上基本正确,然而提交后发现TLE,原因是这种回退的算法,会有很多重复操作,例如前面的例子中,遍历到第二个h的时候,map中已有b,m,h,c,d了,在来个h时,不需要清空map,只需要清空第一个h前面的元素,再把key=h的value覆盖即可。

犯了一些低级的bug后终于ac了~~~TAT

import java.util.HashMap;public class No3_LongestSubstringWithoutRepeatingCharacters {public static void main(String[] args){System.out.println(lengthOfLongestSubstring("wlrbbmqbhcdarzowkkyhiddqscdxrjmowfrxsjybldbefsarcbynecdyggxxpklorellnmpapqfwkhopkmco"));}public static int lengthOfLongestSubstring(String s) {int result = 0;int count = 0;int start = 0;HashMap<Character,Integer> map = new HashMap<Character, Integer>();for(int i=0;i<s.length();i++){if(map.get(s.charAt(i)) == null){count++;map.put(s.charAt(i), i);}else{if(result < count)result = count;//count = 0;//i = map.get(s.charAt(i));//map.clear();int index = map.get(s.charAt(i));index--;while(index >= start && map.get(s.charAt(index)) != null){map.remove(s.charAt(index));index--;}start = map.get(s.charAt(i)) + 1;map.put(s.charAt(i), i);count = map.size();}}if(result < count)result = count;        return result;    }}


0 0
原创粉丝点击