3.Longest Substring Without Repeating Characters

来源:互联网 发布:最新网络征文大赛启事 编辑:程序博客网 时间:2024/05/16 05:11

做了两天,才被accepted。感觉题目挺简单的,关键是算法的时间复杂度。之前没刷过题,没有经验,对于这种类型的题目,一开始想到的就是两层循环,提交之后很悲催地超时。后来慢慢的意识到,子串的起始位置和结束位置都不应该采用递增的赋值方法。总共写了三个版本的代码,第一个就是两层循环,第二个是优化了子串的起始位置,第三个是借鉴了别人的代码后,把HashSet换成了HashMap,第一次使用HashMap。虽然题目很简单,但过程还是有点痛苦,特别是提交之后总提示超时。把代码粘贴下来,记录这个痛苦但有所收获的过程。

第一个版本:两层循环

<span style="white-space:pre"></span>public static int lengthOfLongestSubstring(String s) {int strLength = s.length();int maxLength = 0;int start = -1, end = 0;//每个子字符串的开始位置boolean hasRepeat = false;//针对字符串本身就不是重复的情况Set<Integer> character = new HashSet<Integer>();//两层循环,效率太低,超时,关键在于每个子串起始位置的选择,(第二天)现在想来结束位置也不应该重新赋值for(int i = 0; i < strLength; i++) <span style="white-space:pre"></span>for(int j = i; j < strLength; j++)if(!character.add((int) s.charAt(end))) {//难道耗时在set的插入上?if (maxLength < character.size())maxLength = character.size();maxLength = Math.max(maxLength, end - start);//学了一招hasRepeat = true;character.clear();//开始不够细心,只在重新赋值maxLength时,才清空set集合,应该只要发生插入冲突,就清空start = s.indexOf(s.charAt(end), start);//出现重复字符后,新的子串的起始位置break;}}if(!hasRepeat)maxLength = strLength;                return maxLength;
<span style="white-space:pre"></span>}

第二个版本:优化了子串的起始位置

public static int lengthOfLongestSubstring(String s) {if(s.length() == 0) return 0;//细节int strLength = s.length();int maxLength = 0;int start = -1, end = 0;//每个子字符串的开始位置boolean hasRepeat = false;//针对字符串本身就不是重复的情况Set<Integer> character = new HashSet<Integer>();//两层循环,效率太低,超时,关键在于每个子串起始位置的选择,(第二天)现在想来结束位置也不应该重新赋值while(end < strLength){if(!character.add((int) s.charAt(end))) {//难道耗时在set的插入上?if (maxLength < character.size())maxLength = character.size();maxLength = Math.max(maxLength, end - start);//学了一招hasRepeat = true;character.clear();//开始不够细心,只在重新赋值maxLength时,才清空set集合,应该只要发生插入冲突,就清空start = s.indexOf(s.charAt(end), start);//出现重复字符后,新的子串的起始位置break;}end++;}if(!hasRepeat)maxLength = strLength;        return maxLength;    }

第三个版本:子串的结束位置只需递增1就行了,不需要每次从start开始重新赋值

public static int lengthOfLongestSubstring(String s){if(s == null || s.length() ==0)return 0;int length = 0;//各种细节,应该初始化为1int start = -1, end = 0;HashMap<Character, Integer> map = new HashMap<>();Integer oldIndex = null;while (end < s.length()) {oldIndex = map.put(s.charAt(end), end);if (oldIndex != null && start < oldIndex)start = oldIndex;length = Math.max(length, end - start);end++;}return length;}



做了两天,才被accepted。感觉题目挺简单的,关键是算法的时间复杂度。之前没刷过题,没有经验,对于这种类型的题目,一开始想到的就是两层循环,提交之后很悲催地超时。后来慢慢的意识到,子串的起始位置和结束位置都不应该采用递增的赋值方法。总共写了三个版本的代码,第一个就是两层循环,第二个是优化了子串的起始位置,第三个是借鉴了别人的代码后,把HashSet换成了HashMap,第一次使用HashMap。虽然题目很简单,但过程还是有点痛苦,特别是提交之后总提示超时。把代码粘贴下来,记录这个痛苦但有所收获的过程。
0 0