3. Longest Substring Without Repeating Characters题目和答案详解

1 题目简述

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

给定一个字符串,找到最长的没有重复字符的子串。

Examples:

Given "abcabcbb", theanswer is "abc", which the lengthis 3.

给定字符串 "abcabcbb",答案为长度为3的子串"abc"

Given "bbbbb", theanswer is "b", with the lengthof 1.

给定字符串 "bbbbb",答案为长度为1的子串"b"

Given "pwwkew", theanswer is "wke", with the lengthof 3. Note that the answer must be a substring"pwke" is a subsequence and not a substring.

给定字符串 "pwwkew",答案为长度为3的子串"wke"。注意,答案必须是一个子字符串 "pwke" 是一个子序列而不是一个子字符串。

2 答案详解

(1) 解决思想

  首先,从头开始遍历给定的字符串,找出第一个不含重复字符的子串。例如:给定的字符串为:abcabcd,找到第一个不含重复字符的子串为abc,并将该子串的首字符下标记为pos(此时pos为0),且将该子串的长度记为max_size(此时max_size为3)。

  然后,此时遍历到字符串的第4个字符(a),该字符的上个子串(abc)中含有的字符,故调整遍历范围,从上个子串中重复字符的下一个字符(下标为2)开始遍历,找出下一个不含重复字符的子串。此时找到的子串为bca,但由于该子串的长度<=上个子串的长度,故不需要更新pos和max_size。

  之后,以此类推,找到最长的不含重复字符的子串abcd,更新pos为3,更新max_size为4。

  最后,将给定字符串从pos位置开始,共max_size个字符构造一个字符串string(str,pos,max_size),其中str为给定字符串,并将其返回。

(2) 设计程序

  所设计的程序采用类模板实现,程序如下:

#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

template<class T>
class Solution
{
private:
    T str;
public:
    Solution(const T& s):str(s) {}
    T LongestSubstring();
};

template<class T>
T Solution<T>::LongestSubstring()
{
    if(str.size() < 2) {
        return str;
    }
    int i,j,k(0);
    int pos(0);
    int max_size(0);
    for(i = 1; i < str.size(); i++) {
        j = k;
        while(j < i and str[j] != str[i]) {
            j++;
        }
        if(j < i and max_size < i-k ) {
            max_size = i -k;
            pos = k;
            k = j + 1;
            i = k;
        } else if(j == k) {
            j++;
            k++;
        }
    }
    if(max_size < i -k) {
        pos = k;
        max_size = i -k;
    }
    return T(str,pos,max_size);
}

int main()
{
    const string str1 = "pwwkew";
    const string str2 = "bbbbbb";
    const string str3 = "abcdef";
    Solution<string> sol1(str1);
    Solution<string> sol2(str2);
    Solution<string> sol3(str3);
    cout << "The string:" << str1 << ",the longest substring:"<< sol1.LongestSubstring() << endl;
    cout << "The string:" << str2 << ",the longest substring:"<< sol2.LongestSubstring() << endl;
    cout << "The string:" << str3 << ",the longest substring:"<< sol3.LongestSubstring() << endl;
}
程序运行结果为:

The string:pwwkew,the longest substring:wke
The string:bbbbbb,the longest substring:b
The string:abcdef,the longest substring:abcdef

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值