可以使用哈希表来实现,先将字符串拆分成若干个子串,然后遍历子串,将每个子串存储到哈希表中,如果哈希表中已经存在该子串,则说明字符串中包含重复字符串。

示例代码:

using System.Collections.Generic;

public class Solution {
    public bool ContainsDuplicate(string s) {
        int n = s.Length;
        HashSet<string> set = new HashSet<string>();
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j <= n; j++) {
                string sub = s.Substring(i, j - i);
                if (set.Contains(sub)) {
                    return true;
                } else {
                    set.Add(sub);
                }
            }
        }
        return false;
    }
}

时间复杂度为 $O(n^3)$,空间复杂度为 $O(n^2)$。可以使用滑动窗口来优化时间复杂度。

C# 字符串重复子串检测:哈希表方法与优化

原文地址: https://www.cveoy.top/t/topic/oDlR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录