leetcode problem solve 3——Longest Substring Without Repeating Characters

来源:互联网 发布:java如何输入一个数 编辑:程序博客网 时间:2024/06/03 13:14

            这道题我直接看disscuss了-_-,原因是我对字符串操作很陌生-_-.....看完disscuss代码后,发现字符串的处理没有我想象的那么不能接受,其实背后还是数字嘛(ascii),不要怂,不要怕,下次遇到字符串的题没理由逃避了。

       disscuss里的那个9行c++代码解决这个问题的思路是很好的。

       下面是代码的分析:

        

//寻找最长的子字符串的长度(子字符串中无重复)/*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.*/#include<iostream>#include<vector>#include<string>#include<algorithm>using namespace std;class Solution {public:int lengthOfLongestSubstring(string s){//这种初始化方式:dict包含256个值为-1的元素//相当于用vector建立了一个hash mapvector<int> dict(256, -1);int maxLen = 0, start = -1;for (int i = 0; i != s.length(); i++) {//start的更新//start会被更新为出现次数最多的字符的上一个位置(相对于i),因为每一个字符第一次出现都是-1//不可能大于start,如果一个字符频繁出现,那么其dict[x]会不断更新,然后这个值再来//更新start,所以,start会被更新为出现次数最多的字符的上一个位置(相对于i)。if (dict[s[i]] > start)start = dict[s[i]];//每一次某字母出现的时候,记录下该字母的位置,i就是位置dict[s[i]] = i;//计算最大长度:当前位置i减去start游标的位置maxLen = max(maxLen, i - start);}return maxLen;}};int main(){Solution s;int length = s.lengthOfLongestSubstring("pwwkew");cout << "length is :" << length<<endl;}


阅读全文
0 0
原创粉丝点击