1. 程式人生 > 遊戲攻略 >《艾爾登法環》藍祕密露滴位置說明 藍祕密露滴在哪

《艾爾登法環》藍祕密露滴位置說明 藍祕密露滴在哪

leetcode 3. 無重複字元的最長子串

3. 無重複字元的最長子串

給定一個字串s,請你找出其中不含有重複字元的最長子串的長度。

示例1:

輸入: s = "abcabcbb"
輸出: 3 
解釋: 因為無重複字元的最長子串是 "abc",所以其長度為 3。

示例 2:

輸入: s = "bbbbb"
輸出: 1
解釋: 因為無重複字元的最長子串是 "b",所以其長度為 1。

示例 3:

輸入: s = "pwwkew"
輸出: 3
解釋: 因為無重複字元的最長子串是"wke",所以其長度為 3。
    請注意,你的答案必須是 子串 的長度,"pwke"是一個子序列,不是子串。

提示:

  • 0 <= s.length <= 5 * 104
  • s由英文字母、數字、符號和空格組成
 1 #include <iostream>
 2 #include <unordered_map>
 3 
 4 using namespace std;
 5 
 6 class Solution {
 7 public:
 8     int lengthOfLongestSubstring(string s) {
 9         if (s.size() == 0) {
10             return 0;
11         }
12         unsigned int start = 0;
13         unsigned int
end = 0; 14 unsigned int maxSubStrNum = 0; 15 unordered_map<char, unsigned int> hashMap; // key->字元, value->字元位置 16 for (; end < s.size(); end++) { 17 unordered_map<char, unsigned int>::iterator it; 18 it = hashMap.find(s[end]); 19 if
(it != hashMap.end()) { 20 start = std::max(it->second + 1, start); 21 } 22 maxSubStrNum = std::max(maxSubStrNum, end - start + 1); 23 hashMap[s[end]] = end; 24 } 25 return maxSubStrNum; 26 } 27 }; 28 29 int main() 30 { 31 Solution *test = new Solution(); 32 string s = "abcabcbb"; 33 std::cout << "s: " << s << endl; 34 std::cout << "maxSubstringLen:"<< test->lengthOfLongestSubstring(s) << endl; // 3 35 36 s = ""; 37 std::cout << "s: " << s << endl; 38 std::cout << "maxSubstringLen:"<< test->lengthOfLongestSubstring(s) << endl; // 0 39 40 s = "bbbb"; 41 std::cout << "s: " << s << endl; 42 std::cout << "maxSubstringLen:"<< test->lengthOfLongestSubstring(s) << endl; // 1 43 44 s = "pwwkew"; 45 std::cout << "s: " << s << endl; 46 std::cout << "maxSubstringLen:"<< test->lengthOfLongestSubstring(s) << endl; // 3 47 48 delete test; 49 system("pause"); 50 return 0; 51 }