一、 问题描述
Leecode第三题,题目为:
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)从字符串第一个字符至最后一个字符顺序遍历字符串,并标记该不重复字符串的长度,for example:len=k,(k为不重复字符串的长度);
(2)继续遍历字符串,如果有不重复字符串length大于已标记字符串长度,那么更新符号变量的值,否则,继续遍历,直至最后一个字符串。
(3)返回最长字符串的内容及长度。
三、实现代码
class Solution {
public:int lengthOfLongestSubstring(string s) {string max_string = ""; string goal = ""; char ch; for(int i=0; i<s.length(); i++){ ch = s[i];int idx = goal.find(ch);if(idx==string::npos){ goal += s[i];} else{ goal = goal.substr(idx+1);goal += s[i];} if(goal.length()>=max_string.length()){ max_string = goal;} } return max_string.length();}
};