Longest Substring Without Repeating Characters

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.

这道题开始的思路复杂度为n^2,想法是外层循环控制总方向,内存循环控制外层循环定位的方向,结果是运行时间超时。看了别人的解法之后,发现可以是n来实现,只有一层循环控制,并且可以步进移动。当碰到有重复的字符时,直接跳到重复的值索引后一位,然后继续寻找,因此就是如下解法。

class Solution {
public:   
    int lengthOfLongestSubstring(string s) {     
        if(s.empty())
            return 0;
        int i,maxLength = 0;
        string temp;
        for(i=0;i<strlen(s.c_str());i++){
            if(temp.find(s[i]!=temp.npos)){
                temp = temp.substr(temp.find(s[i])+1,strlen(temp.c_str()));
            }
            temp = temp + s[i];
            maxLength = max(maxLength,strlen(temp.c_str()));
        }  
        return maxLength;
    }
    int max(int a,int b){
        return a>b?a:b;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容