美文网首页
查找字符串中最长不重复的子字符串

查找字符串中最长不重复的子字符串

作者: DDDDAIPING | 来源:发表于2020-01-19 11:25 被阅读0次

直接上代码

std::tuple<int, int> _findLongestSubString(const char* str) {
    int index = -1, len = -1;
    if (NULL == str) {
        return std::make_tuple(index, len);
    }
    bool isRepetitive = false;
    int strLen = int(strlen(str));
    for (int i = 0; i < strLen; i++)
    {
        isRepetitive = false;
        for (int j = i + 1; (j <= strLen) && !isRepetitive; j++)
        {
            for (int k = i; k < j; k++) {
                if (str[k] == str[j]) {
                    isRepetitive = true;
                    break;
                }
            }
            if ((j - i) > len)
            {
                index = i;
                len = j - i;
            }
        }
    }
    return std::make_tuple(index, len);
}

简单测试

#include <tuple>
#include <iostream>
int main(int argc, char** argv)
{
    //abcdefgaaabcefadfasdldf abceabcaasdesadfsafwqa abcdefgjiljklafam aabbccddabc
    const char* abc = "abcabceefbb";
    int index, len;
    std::tie(index, len) = _findLongestSubString(abc);
    char buf[128] = {};
    strncpy_s(buf, abc + index, len);
    printf("source:[%s]\nIndex:%d\tLen=%d\nsubstr=[%s]\n", abc, index, len, buf);
    return 0;
}
游标法

使用两个游标在原字符串上,来回移动;
主要思路,使用最外层循环来确定子字符串在原字符串中开始坐标,使用中层循环来确定子字符串长度,使用内层循环来确定是否有字符重复。

相关文章

网友评论

      本文标题:查找字符串中最长不重复的子字符串

      本文链接:https://www.haomeiwen.com/subject/wskrzctx.html