当前位置: 代码迷 >> 综合 >> leetcode练习题 longest-substring-without-repeating-characters
  详细解决方案

leetcode练习题 longest-substring-without-repeating-characters

热度:55   发布时间:2023-12-15 09:56:54.0

解题思路

用一个res保存当前的最长不重复子串,之后遍历字符串,设置当前的最长不重复子串为当前字符,之后从该字符的后一个字符串开始,若当前的最长不重复子串不包含该字符,则将该字符包含进来,否则break。之后与res进行比较,用res保存较大值。字符串遍历结束后res即为结果。

代码

class Solution {
public:int lengthOfLongestSubstring(string s) {int res = 0;for(int i = 0;i < s.size();i++){string longest = "";longest += s[i];int j = i + 1;while(j < s.size()){if(longest.find(s[j]) == string::npos)longest += s[j];elsebreak;j++;}int len = j - i;res = (res > len) ? res : len; }return res;}
};
  相关解决方案