码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 3. Longest Substring Without Repeating Characters(medium难度)【精】

时间:2017-12-07 21:05:32      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:substr   without   优秀   搜索   难度   examples   位置   color   font   

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.

 

 题目很通俗易懂,就是找一个字符串中,没有重复字符的最长子串的长度。说实话,这道中等难度的题目卡了我很久,最后把它想明白时,内心还是有些小小的激动的。其实不仅是刷题,人生中很多其他方面的事情也都需要有一个积极的心态,不断给自己积极的心理暗示,这样结果一般真的就能如你所愿。

回归正题,这道题暴力搜索法复杂度是O(n^3),这也很好理解,两个指针分别指向字符串的首尾,两重循环,每次都需要判断两个指针之间是否有重复的字符,我们在面试时可以第一时间向面试官讲出这样的思路,至少可以从侧面展现出我们思维敏捷的特点,后续的改进再聊。刷题时,这个复杂度肯定会超时,我们需要进一步改进它。我这里直接把最优解的代码贴出来,时间复杂度为O(n)之后我再解释为何这样做,代码如下:

 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4         //这道题目还是很不错的,参考着优秀解答写一般,O(n)复杂度,以空间换时间。
 5         vector<int> mymap(256,-1);
 6         int i,last=0,ans=0;
 7         for (int i = 0; i < s.length(); i++)
 8         {
 9             if (mymap[s[i]] == -1 || mymap[s[i]] < last)  //如果该字符没有出现过
10                 ans = max(ans, i - last + 1);
11             else
12                 last = mymap[s[i]] + 1;
13             mymap[s[i]] = i;
14         }
15         return ans;
16      
17     }
18 };

解释一下思路:last表示字符串开始的位置,

 

LeetCode 3. Longest Substring Without Repeating Characters(medium难度)【精】

标签:substr   without   优秀   搜索   难度   examples   位置   color   font   

原文地址:http://www.cnblogs.com/dapeng-bupt/p/8000381.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!