leetcode题3 寻找字符串不包含重复字符的最长子字符串
来源:互联网 发布:嫁给老男人 知乎 编辑:程序博客网 时间:2024/05/20 20:22
决定每天刷一道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题3 寻找字符串不包含重复字符的最长子字符串
- Leetcode.寻找不重复的最长子字符串
- leetcode 3-最长无重复字符的子字符串
- 寻找字符串最长不重复的子串
- 求字符串中不包含重复字符的最长子串的长度
- 求字符串内不包含重复字符的最长子串的集合
- 求字符串内不包含重复字符的最长子串
- 求字符串中不重复字符的最长子串
- 字符串最长不含重复字符的子串长度
- 最长不含重复字符的子字符串
- lc#3求字符串中不包含重复字符的最大长度子串
- 【LeetCode题目记录-3】字符串中最长的没有重复字符的子串
- 从字符串中找出一个最长的不含重复字符的子字符串
- 寻找字符串的最长不重复子串,计算复杂度O(n),两种实现
- LeetCode 题解 3. Longest Substring Without Repeating Characters(最长不含重复字符的子字符串)
- LeetCode 3. Longest Substring Without Repeating Characters--不包含重复字符的最长子串长度
- 从字符串S中找出不包含重复字符的最大连续子字符串长度
- leetcode--3--最长不重复字符串
- C 语言泛型Array数组封装
- intellij idea maven 工程junit4单元测试
- 对于移动平均算法,是计算某变量之前n个数值的算术平均,正确的说法是:----腾讯2016研发工程师在线模拟笔试题
- Spring:传统的XML文件装配Bean
- PAT乙级练习题B1040. 有几个PAT
- leetcode题3 寻找字符串不包含重复字符的最长子字符串
- java中String、StringBuffer、StringBuilder的区别
- 泛型的使用
- 浏览器输入网址后台是如何运作的
- Tomcat登录Manager登录不成功
- LeetCode 234. Palindrome Linked List判断链表是否回文
- PAT乙级练习题B1037. 在霍格沃茨找零钱
- Codeforces 552.C Vanya and Scales
- CollapsingToolbarLayout