求字符串最长连续不重复的字串

思路:dp[c]记录字符c上一次出现的位置。l记录上一个连续不重复字串的左边界,这样就可以更新连续不重复子串的长度。我这里输出的是第一次出现的最长的连续不重复子串。

#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <cmath>
#include <set>
#include <map>
using namespace std;

typedef long long LL;
#define mem(a, n) memset(a, n, sizeof(a))
#define ALL(v) v.begin(), v.end()
#define si(a) scanf("%d", &a)
#define sii(a, b) scanf("%d%d", &a, &b)
#define siii(a, b, c) scanf("%d%d%d", &a, &b, &c)
#define pb push_back
#define eps 1e-8
const int inf = 0x3f3f3f3f, N = 1e3 + 5, MOD = 1e9 + 7;

int T, cas = 0;
int n, m;
int dp[105];
char s[N];

#define LOCAL
int main(){
#ifdef LOCAL
    freopen("/Users/apple/input.txt", "r", stdin);
//    freopen("/Users/apple/out.txt", "w", stdout);
#endif
    
    while(scanf("%s", s) != EOF) {
        int len = strlen(s);
        mem(dp, -1);
        int ul = -1, ur = -1, l = -1, ans = 0;
        for(int r = 0; r < len; r ++) {
            int index = dp[s[r]] + 1;
            dp[s[r]] = r;
            l = max(l, index);
            if(r - l + 1 > ans) {
                ans = r - l + 1;
                ul = l, ur = r;
            }
        }
        printf("[%d, %d]\n", ul, ur);
        for(int i = ul; i <= ur; i ++) putchar(s[i]); puts("");
    }
    
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Python的一些字符串处理方法来实现找到字符串最长重复子串的长度。 首先,定义一个字典来记录字符和其在字符串的位置。然后,定义两个变量:max_length用于记录最长重复子串的长度,start用于记录当前子串的起始位置。 遍历整个字符串,对于每一个字符: 1. 如果字符在字典不存在,或者在当前子串的位置小于start,说明该字符是一个新的不重复字符,可以继续扩展当前子串的长度。 2. 否则,将当前子串的长度与max_length比较,更新max_length为较大的值,并将start更新为当前字符在字典的位置加1,表示以当前字符为起始的新的子串。 最后返回max_length即可。 以下是代码示例: ```python def find_longest_substring_length(s): char_dict = {} # 字典用于记录字符和其在字符串的位置 max_length = 0 # 最长重复子串的长度 start = 0 # 当前子串的起始位置 for i, char in enumerate(s): if char not in char_dict or char_dict[char] < start: # 如果字符是一个新的不重复字符,更新字典和最长子串长度 char_dict[char] = i else: # 否则,更新max_length为较大的值,并更新start max_length = max(max_length, i - start) start = char_dict[char] + 1 char_dict[char] = i # 检查最后一个子串的长度 max_length = max(max_length, len(s) - start) return max_length s = "pwwkew" length = find_longest_substring_length(s) print(length) ``` 输出结果为3,表示字符串最长重复子串的长度为3("wke")。 注意:这个方法只能找到最长重复子串的长度,如果需要得到最长子串本身,需要进行一些额外的处理。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值