LeetCode算法问题7 —— Longest Substring Without Repeating Characters

问题描述
这里写图片描述

简单来说,就是找一个字符串中最长的不存在重复字母的子串长度

自然遍历字符串一遍是不可避免的,自然,我的想法就是建立一个临时字符串变量temp存储当前遍历到的无重复字母的字符串,在对给定字符串进行遍历的时候,可能会出现几种情况:

  1. 不是重复字母,则temp将其加上
  2. 是重复字母,则:
    a. 首先比较当前temp长度和目前所遇到的最长长度哪个大,若是temp较长则替换
    b. 如果重复字母出现在temp的中间,则中间及以前的字符串都必须剔除,新的temp是重复字母之后的子串与重复字母的合
    c. 如果重复字母出现在末位,则temp元素全部替换

下面是源代码:

int lengthOfLongestSubstring(string s) {
        string temp;
        int biggestLength = 0;
        size_t pos;
        for (int i = 0; i < s.size(); i++) {
            pos = temp.find(s[i]);
            if (pos != string::npos) {
                if (temp.size() > biggestLength)
                    biggestLength = temp.size();
                /* The repeating character isn't in the end of the string "answer" */
                if (pos != temp.size() - 1) {
                    temp = temp.substr(pos + 1) + s[i];
                } else {
                    temp = s[i];
                }
            } else {
                temp += s[i];
            }
        }
        if (temp.size() > biggestLength)
            biggestLength = temp.size();
        return biggestLength;
    }

时间复杂度是O(n),暂且没有找到更好的办法,希望能获取大家的建议

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值