Leecode:Longest Substring Without Repeating Characters

Description:

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.

1、问题描述
给定一个字符串,找其无重复字符的最长子串的长度。
2、算法分析

遍历字符串,同时往前遍历前面的字符,如果前面有重复的,就把前面离现在这个字符最近的重复的字符的索引记录在flag;如果没有重复,则flag保持不变;count记录每一个无重复字符的子串长度。本算法采用双重循环,算法时间复杂度为O( n2 ),Runtime为25ms。注意: 第二重循环的下标要大于最近记录的flag

3、代码
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int maxlen = 0, flag = -1;
        int count = 0;
        int length = s.length();
        if (length == 1) return true;
        for (int i = 1; i < length; ++i) {
            count = 1;
            for (int j = i-1; j >= 0; --j) {
                if (s[i] == s[j]) {
                    if (j > flag) flag = j;
                    break;
                }
                if (j == flag) break;
                count++;
            }
            if (maxlen < count) maxlen = count; 
        }
        return maxlen;
    }
};
4、其他优化算法分析

可以用hash表的方法来降低时间复杂度:用一个hash table保存每个字符上一次出现过的位置。从前往后扫描,假如发现字符上次出现过,就把当前子串的起始位置start移动到上次出现过的位置之后(为了保证从start到i的当前子串中没有任何重复字符)。同时,由于start移动,当前子串的内容改变,start移动过程中经历的字符都要剔除。 复杂度为O(n),Runtime为12ms,代码如下

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int start = 0; 
        int maxlen = 0;
        int table[256]; // hash table  
        for (int i = 0;i < 256;i++) table[i] = -1;
        int len = s.length();  
        for (int i = 0;i < len;i++) {  
            if (table[s[i]] != -1) {  
                while (start <= table[s[i]]) table[s[start++]] = -1;  
            }  
            if (i - start + 1 > maxlen) maxlen = i - start + 1;  
            table[s[i]] = i;  
        }  
        return maxlen;  
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值