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.");
            }
  • 相关阅读:
    梦断代码阅读笔记之三
    梦断代码阅读笔记二
    输入法评价
    1的个数
    团队冲刺-10
    第一阶段个人总结03
    第一阶段个人总结02
    第一阶段个人总结01
    学习进度条第十周
    学习进度条第九周
  • 原文地址:https://www.cnblogs.com/Ligeance/p/2770891.html
Copyright © 2011-2022 走看看