您的位置:首页 > 其它

leetcode题3 寻找字符串不包含重复字符的最长子字符串

2016-07-10 19:52 337 查看
决定每天刷一道leetcode题来维持编程和学习的状态

问题表述

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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法