标签:har unmap input output max eating for sts ==
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew" Output: 3 Explanation: 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.
1 class Solution { 2 public: 3 int lengthOfLongestSubstring(string s) 4 { 5 // 定义一个map用来存放整个字符串s 6 unordered_map<char, int> unmap; 7 8 // tempLength记录每次扫描位置开始的一次统计的最长字符串的长度 9 int tempLength = 0; 10 // 众多tempLength中的最大值 11 int maxLength = 0; 12 13 // 第一层循环:分别以s中的每个字符为基准,进行遍历 14 for (int j = 0; j < s.size(); j++) 15 { 16 // 第二层循环:以当前第一层循环中当前的字符为基准,进行遍历,统计以此字符为基准的tempLength 17 for (int i = j; i < s.size(); i++) 18 { 19 // 是否tempLength继续增加的条件是,map中没有出现过当前指向的字符 20 if (unmap.count(s[i]) == 0) 21 { 22 pair<char, int> myshopping(s[i], i); 23 // 如果当前的map中无此字符,将当前字符插入到map中 24 unmap.insert(myshopping); 25 tempLength++; 26 maxLength = maxLength > tempLength ? maxLength : tempLength; 27 } 28 // 当前字符已经在map中了,直接break,并将本次使用的map进行清除操作 29 else 30 { 31 32 tempLength = 0; 33 unmap.clear(); 34 break; 35 } 36 37 } 38 } 39 40 return maxLength; 41 } 42 };
【LeetCode刷题系列 - 003题】Longest Substring Without Repeating Characters
标签:har unmap input output max eating for sts ==
原文地址:https://www.cnblogs.com/xuelisheng/p/10771848.html