Leetcode刷題:3. Longest Substring Without Repeating Characters

題目:

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.


思路:

題目要求的是沒有重複字符的最長子字符串的長度

檢查重複顯然可以用 k-v mapping.所以剩下只需要考慮如何在一次迭代遍歷過程中度量子串長度。

charpos
a0
b1
c2

如上圖所示:將char和各自的索引值組成kv-mapping,用trace存儲更新不重複的char,通過查詢當前trace表就可知,是否呦重複字母出現,若pos >= start,故此刻誕生一個 substr. 長度爲i-start,start更新爲pos+1.


代碼:

/*
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.
*/

#include <string>
#include <unordered_map>
#include <algorithm>

using namespace std;

class Solution {
public:
	int lengthOfLongestSubstring(string s) {
		// 創建kv-map
		unordered_map<char, size_t> trace;
		// 創建重新搜索的起始索引變量
		size_t start = 0;
		// 記錄歷史最長子串長度變量
		size_t rec = 0;

		// 一次遍歷
		for (size_t i = 0; i != s.size(); i++)
		{
			// 搜索當前索引對應的char之前是否出現過
			auto found = trace.find(s[i]);
			// 如果出現過,說明該索引之前的子串爲最大子串
			if (found != trace.end() && found->second >= start)
			{
				// 計算此次的最大子串的長度
				//rec = i - found->second;
				// 比較此次的最大子串的長度和歷史長度,記錄最大值
				rec = max(rec, i - start);
				// 將下次搜索的起始索引重置爲前面重複字母索引+1
				start = found->second + 1;
			}
			// 更新trace
			trace[s[i]] = i;
		}

		// 遍歷完畢再做最後一次比較
		rec = max(rec, s.size() - start);

		return rec;
	}
};

發佈了33 篇原創文章 · 獲贊 19 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章