题目:
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.
代码(C++实现):
class Solution {
public:
int lengthOfLongestSubstring(string s)
{
// 定义一个map用来存放整个字符串s
unordered_map<char, int> unmap; // tempLength记录每次扫描位置开始的一次统计的最长字符串的长度
int tempLength = ;
// 众多tempLength中的最大值
int maxLength = ; // 第一层循环:分别以s中的每个字符为基准,进行遍历
for (int j = ; j < s.size(); j++)
{
// 第二层循环:以当前第一层循环中当前的字符为基准,进行遍历,统计以此字符为基准的tempLength
for (int i = j; i < s.size(); i++)
{
// 是否tempLength继续增加的条件是,map中没有出现过当前指向的字符
if (unmap.count(s[i]) == )
{
pair<char, int> myshopping(s[i], i);
// 如果当前的map中无此字符,将当前字符插入到map中
unmap.insert(myshopping);
tempLength++;
maxLength = maxLength > tempLength ? maxLength : tempLength;
}
// 当前字符已经在map中了,直接break,并将本次使用的map进行清除操作
else
{ tempLength = ;
unmap.clear();
break;
} }
} return maxLength;
}
};