【leetcode】3.Longest Substring Without Repeating Characters
2017-08-22 13:09
375 查看
一.问题描述
DescriptionGiven a string, find the length of the longest substring without repeating characters.
给定一个字符串,找到其中的一个最长的字串,使得这个子串不包含重复的字符。
Example
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.
二、问题分析及源代码
看到这个题目,首先我是想到了hashmap,先将字符串遍历存入hashmap中,并用value记录每一个字符的位置,当某个字符在hashmap中已存在时,结束这一轮遍历,同时记录此次遍历的字符串长度,将遍历字符串的start置为该已存在字符的下一个,并将已遍历的字符串移除,重新开始一轮遍历。但是,如abcdeaf,第一轮遍历后start=2,此时又要把bcdeaf遍历一次,无疑是浪费时间。最后的解决方法时,当进行新一轮遍历时,以abcdeaf为例,start =2,而在第一轮遍历中,bcdea已经确定之间不含有重复字符,所以此时,end便可以置为f所在的位置,即上轮遍历中的end+1,进行这一轮的遍历。
c++的代码如下:
#include<iostream> using namespace std; class Solution { public: int lengthOfLongestSubstring(string s) { int len = s.length(); int start = 0,end = 0; int max_length = 0; int now_length = 0; bool exits[256] = {false}; while(end<len){ if(!exits[s[end]]){ exits[s[end]] = true; end++; }else{ while(s[start]!=s[end]){ exits[s[start]] = false; start++; } start++; end++; } now_length = end-start; max_length = max_length > now_length?max_length:now_length; } return max_length; } }; int main(){ Solution s; int l = s.lengthOfLongestSubstring("pwwkew"); cout<<l; }
可以说是零c++基础,在此记录:
class Test{
private:
int a;
public:
getA(){}
};
//主函数
int main(){
//1.
Test t;
t.getA();
//2.
Test *t = new Test();
t->getA();
}
相关文章推荐
- Leetcode—3.Longest Substring Without Repeating Characters
- [leetcode] 3.Longest Substring Without Repeating Characters
- LeetCode - 3.Longest Substring Without Repeating Characters
- LeetCOde------3.Longest Substring Without Repeating Characters
- LeetCode-3.Longest Substring Without Repeating Characters
- [leetcode]3.longest substring without repeating characters
- LeetCode 3.longest-substring-without-repeating-characters
- 【leetcode】3.Longest Substring Without Repeating Characters
- 个人记录-LeetCode 3.Longest Substring Without Repeating Characters
- [leetcode] 3.Longest Substring Without Repeating Characters
- leetcode - 3.Longest Substring Without Repeating Characters
- LeetCode 3.Longest Substring Without Repeating Characters
- 【leetcode】3.Longest Substring Without Repeating Characters
- LeetCode题解 C++ Longest Substring Without Repeating Characters
- [LeetCode]Longest Substring Without Repeating Characters
- LeetCode题库解答与分析——#3.无重复字符的最长子串LongestSubstringWithoutRepeatingCharacters
- leetcode3 Longest Substring Without Repeating Characters
- LeetCode 3 Longest Substring Without Repeating Characters
- LeetCode: 3_Longest Substring Without Repeating Characters | 求没有重复字符的最长子串的长度 | Medium
- LeetCode 3:Longest Substring Without Repeating Characters