leetcode题3 寻找字符串不包含重复字符的最长子字符串
2016-07-10 19:52
337 查看
决定每天刷一道leetcode题来维持编程和学习的状态
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.
Subscribe to see which companies asked this question
问题表述
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.
Subscribe to see which companies asked this question
求解思路
粗看这题并不难,最开始的想法是使用分而治之策略,但是细细思考之后,这个问题分是很容易的,但是合并却不是很容易,于是放弃了这种想法。第二种想法是动态规划,看起来也确实是可行的,我最初也是用动态规划来实现的,但是在测试之后却发现有些测试用例有问题,调试了一下才发现动态规划的递推关系并没有我想象当中的简单,典型的就是没有想好就开始写程序,结果做了很多无用功。最后我发现其实只要从左到右把字符串扫描一遍就可以找到结果。我们维护两个字符串,一个是当前最大的字符串,一个是当前的字符串,最初的时候这两个字符串都为空。每扫面一个字符,如果这个字符不在字符串当中,我们就把当前字符串加上这个字符。如果在,当前字符串就不能再往前加字符了,我们需要比较当前字符串和当前最大字符串。为了满足子字符串不能有重复元素的要求,我们需要把当前字符串的开始地址替换掉。如此扫面一遍,就能够得出结果。Java代码
public class Solution { public static int lengthOfLongestSubstring(String s){ int start = 0; String max = ""; String current = ""; int pos; for(int i = 0;i<s.length();i++){ if(current.indexOf(s.charAt(i)) != -1){ if(current.length() >= max.length()){ max = current; } pos = current.indexOf(s.charAt(i)); current = s.substring(start + current.indexOf(s.charAt(i))+1, i+1); start = start + pos + 1; } else{ current = current + s.charAt(i); } } return max.length() > current.length()? max.length() : current.length(); } }
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- C#递归算法之分而治之策略
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- C#算法之大牛生小牛的问题高效解决方法
- C#算法函数:获取一个字符串中的最大长度的数字
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- 经典排序算法之冒泡排序(Bubble sort)代码
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法