字符串算法-找到其中不含重复字符的最长子串的长度(滑动窗口或暴力法)

//字符串算法
//题目:给定一个字符串,找到其中不含重复字符的最长子串的长度。
//
//问题函数定义:
//
//cpp
//int lengthOfLongestSubstring(const std::string& s);
//裁判测试程序样例:
//
//cpp
#include<iostream>
#include<stack>
#include <vector>
#include<string>
#include<algorithm>
#include<unordered_map>
#include <climits>
#include<queue>
#include<unordered_set>
#include<cctype>
using namespace std;

//1.滑动窗口法(推荐O(n))

int lengthOfLongestSubstring(const std::string& s) {
    unordered_map<char, int> charIndexMap;
    int start = 0;
    int maxlen = 0;

    for (int end = 0; end < s.length(); end++) {
        if (charIndexMap.find(s[end]) != charIndexMap.end()) {
            // 如果当前字符已经在窗口中出现过,则更新窗口的起始位置
            start = max(start, charIndexMap[s[end]] + 1);
        }
        // 更新当前字符的最新位置
        charIndexMap[s[end]] = end;
        // 更新最大子串长度
        maxlen = max(maxlen, end - start + 1);
    }

    return maxlen;
}
int main() {
    std::string s = "abcabcbb";
    std::cout << "Length of longest substring without repeating characters: " << lengthOfLongestSubstring(s) << std::endl;
    return 0;
}
//输入样例:
//
//s = "abcabcbb"
//输出样例:
//
//Length of longest substring without repeating characters : 3

//2.暴力遍历法O(n^2)

int lengthOfLongestSubstring(const std::string& s) {
    int start = 0;
    int maxlen = 1;
    int len = 1;
    for (int i = 1; i < s.length(); i++) {
        len++;
        for (int j = start; j <= i - 1; j++) {
            if (s[i] == s[j]) {
                start = max(j + 1,start);
                len = i - j;
            }
        }
        maxlen = max(len, maxlen);
    }
    return maxlen;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值