3. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", 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.


由题意得,找出有着不重复字符的最长的字符串的长度。题目挺简单的,每次都记录字符串开始的位置start,还有在判断是否重复的时候需要记录重复的下标index,然后遇到重复字符之后的开始位置则为start + index + 1。主函数里是遍历一遍字符串就好了,但是在判断重复字符则也要遍历一遍,所以时间复杂度最坏是在O(n^2),平均为O(nlogn),代码如下:

Code(LeetCode运行32ms):

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int Max = 0;
        int length = 0;
        int index = 0;
        int start = 0;
        string temp = "";
        for(int i = 0; i < s.length(); i++) {
            if (!isRepeating(s[i] , temp, index)) {
                length++;
            } else {
                Max = max(length, Max);
                length = temp.length() - index;
                start = start + index + 1;
                temp = s.substr(start, length - 1);
            }
            temp += s[i];
        }
        Max = max(length, Max);
        return Max;
    }
    bool isRepeating(char c, string s, int& index) {
        for (int i = 0; i < s.length(); i++) {
            if (c == s[i]) {
                index = i;
                return true;
            }
        }
        return false;
    }
};
假如改良一下判断重复这一部分的算法,那么可以得到一个O(n)的算法,参考了LeetCode里面大神的做法,使用一个数组来保存某字符上次出现的位置。
Code(LeetCode运行18ms):

int lengthOfLongestSubstring(string s) {
        const int ASCII_MAX = 255;
        int last[ASCII_MAX];
        int start = 0;
        fill(last, last + ASCII_MAX, -1);
        int max_len = 0;
        for (int i = 0; i < s.length(); i++) {
            if (last[s[i]] >= start) {
                max_len = max(max_len, i - start);
                start = last[s[i]] + 1;
            }
            last[s[i]] = i;
        }
        return max((int)s.length() - start, max_len);
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值