You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现提取唯一字符字符串并获取最长重复字符子串长度的方法

C# 解决方案

方法实现

以下方法完成需求:生成符合要求的去重字符串(支持两种逻辑,可按需切换),并返回最长重复字符子串的长度。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class StringProcessor
{
    // 返回值:(处理后的字符串, 最长重复字符子串长度)
    public static (string UniqueString, int LongestRepeatingSubstringLength) ProcessString(string input)
    {
        if (string.IsNullOrEmpty(input))
        {
            return (string.Empty, 0);
        }

        // 统计每个字符的出现次数
        var charCount = input.GroupBy(c => c)
                             .ToDictionary(group => group.Key, group => group.Count());

        // --- 任务1:生成仅含不重复字符的新字符串 ---
        // 逻辑1:去重,保留每个字符的首次出现(新字符串无重复字符)
        var uniqueSet = new HashSet<char>();
        var uniqueSb = new StringBuilder();
        foreach (char c in input)
        {
            if (uniqueSet.Add(c))
            {
                uniqueSb.Append(c);
            }
        }
        var resultString = uniqueSb.ToString();

        // 逻辑2:仅保留原字符串中出现次数为1的字符(去掉所有重复出现过的字符)
        // var uniqueSb = new StringBuilder();
        // foreach (char c in input)
        // {
        //     if (charCount[c] == 1)
        //     {
        //         uniqueSb.Append(c);
        //     }
        // }
        // var resultString = uniqueSb.ToString();

        // --- 任务2:计算最长重复字符子串长度 ---
        // 定义:子串中的每个字符在原字符串中出现次数≥2,找最长连续子串的长度
        int maxLength = 0;
        int currentLength = 0;
        foreach (char c in input)
        {
            if (charCount[c] >= 2)
            {
                currentLength++;
                maxLength = Math.Max(maxLength, currentLength);
            }
            else
            {
                currentLength = 0;
            }
        }

        return (resultString, maxLength);
    }

    // 测试示例
    public static void Main()
    {
        string input = "aqaswasldkaslfaslyetdop";
        var (uniqueStr, longestLength) = ProcessString(input);
        Console.WriteLine($"处理后的字符串:{uniqueStr}");
        Console.WriteLine($"最长重复子串长度:{longestLength}");
    }
}

关键逻辑说明

  1. 字符计数:通过GroupBy统计每个字符的出现次数,为两个任务提供数据支撑。
  2. 去重字符串生成:
    • 逻辑1用HashSet跟踪已添加字符,确保新字符串无重复,同时保留原字符串的首次出现顺序。
    • 逻辑2仅保留原字符串中只出现过一次的字符,完全排除所有重复出现过的字符。
  3. 最长重复子串计算:遍历原字符串,连续统计由重复字符(出现次数≥2)组成的子串长度,记录最大值。

示例测试

运行Main方法,输入"aqaswasldkaslfaslyetdop":

  • 若使用逻辑1,处理后的字符串为"aqswldkfyetop",最长重复子串长度为4。
  • 若使用逻辑2,处理后的字符串为"qwkfyetop",最长重复子串长度仍为4。

内容的提问来源于stack exchange,提问作者Yaroslav Parkhomenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 13:47:39