zoukankan      html  css  js  c++  java
  • C# 移动第一个重复字符到前面

    例如 abcdbbfg 变成 bbbacdfg,要求时间复杂度为N,空间复杂度为1,写了两个方法都未达到要求 :(

    View Code
            static void MoveDupCharToFront(char[] input)
            {
                if (input == null|| input.Length <=1)
                {
                    throw new Exception("input can't be empty or less than 2 length");
                }
                int dupCount = 0;
                int x = 0;
                char dupChar = FindFirstDupChar(input);
                char[] result = new char[input.Length];
                for (int i = 0; i < input.Length; i++)
                {
                    if (input[i] == dupChar)
                    {
                        dupCount++;
                    }
                }
    
                while (dupCount >0)
                {
                    result[x++] = dupChar;
                    dupCount--;
                }
                for (int i = 0; i < input.Length; i++)
                {
                    if (input[i]!=dupChar)
                    {
                        result[x++] = input[i];
                    }
                }
                input = result;
            }
    
            static void MoveDupCharToFront2(char[] input)
            {
                if (input == null|| input.Length <=1)
                {
                    throw new Exception("input can't be empty or less than 2 length");
                }
                char dupChr = FindFirstDupChar(input);
                for (int i = 0; i < input.Length; i++)
                {
                    if (input[i]== dupChr)
                    {
                        for (int j = i; j >0; j--)
                        {
                            input[j] = input[j - 1];
                        }
                        input[0] = dupChr;
                    }
                }
            }
    
            static char FindFirstDupChar(char[] input)
            {
                if (input == null || input.Length ==0)
                {
                    throw new Exception("input can't be empty .");
                }
                Hashtable ht = new Hashtable();
                for (int i = 0; i < input.Length; i++)
                {
                    if (ht[input[i]] == null)
                    {
                        ht.Add(input[i], 1);
                    }
                    else
                    {
                        return input[i];
                    }
                }
                throw new Exception("No dup char.");
            }
  • 相关阅读:
    vue学习目录
    充分利用 SQL Server Reporting Services 图表
    MSCRM 用户登录日志
    Microsoft Dynamics CRM MVP
    在SSRS 里实现 SUMIF
    MSCRM 报表显示 rsprocessingaborted 错误
    电商CRM的痛点在哪里?
    MSCRM 2011/2013/2015 修改显示记录数
    MSCRM 2013/2015 Ribbon Editor
    Q:解决每天第一次打开MSCRM系统展示慢的问题
  • 原文地址:https://www.cnblogs.com/Ligeance/p/2770891.html
Copyright © 2011-2022 走看看