leetcode problem solve 3——Longest Substring Without Repeating Characters

            這道題我直接看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 map
		vector<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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章