第八周作业1(LeetCode3)

1. 题目描述(LeetCode3)

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.

2. 解决思路

这道题的关键是如何在遍历一遍字符串的时间复杂度(O(n))的情况下截取子字符串并同时判断子字符串中有无重复的字符。根据提示,我们可以利用hash表hashTable[256]来保存出现过的字符,然后从头开始遍历字符串,在遍历过程中根据判断当前字符串有无出现而进行相应的操作:
1、如果当前字符串已经出现过(hashTable[str[idx]] == 1),则说明一个局部最长不重复的子串已经出现:此时判断该子串长度len是否大于mlen,若 大于则更新mlen,以及最长子串的起始位置mstart;同时将start到重复字符之间的hash表重置为0(表示没有出现过),相应的长度len也减小,然后从str[idx]的下个字符作为新的子串的开始。
2、如果当前字符ch没有出现过,则设置hashTable为1(表示出现过),并len ++。

3. 完整代码

#include <iostream>
#include <string>
using namespace std;


int getLongestUnRepeatedSubstr(const string &str){
    int hashTable[256] = {0};
    int start = 0;
    int mstart = 0;
    int mlen = 0;
    int idx = 0;
    int len = 0;
    while (idx != str.size()){
        if (hashTable[str[idx]] == 1){
            if (len > mlen){
                mstart = start;
                mlen = len;
            }
            while (str[start] != str[idx]){
                hashTable[str[start]] = 0;
                start++;
                len--;
            }
            start++;
        }
        else{
            hashTable[str[idx]] = 1;
            len++;
        }
        idx++;
    }

    if (len > mlen)
    {
        mlen = len;
        mstart = start;
    }
    cout << str.substr(mstart, mlen) << endl;
    return mlen;

}

int main(){
    string str;
    while (cin >> str){
        cout << getLongestUnRepeatedSubstr(str) << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值