【问题标题】:function to remove duplicate characters in a string删除字符串中重复字符的函数
【发布时间】:2010-04-08 07:06:55
【问题描述】:

以下代码试图删除字符串中的所有重复字符。我不确定代码是否正确。谁能帮我处理代码(即当字符匹配时实际发生了什么)?

public static void removeDuplicates(char[] str) {
  if (str == null) return;
  int len = str.length;
  if (len < 2) return;
  int tail = 1;
  for (int i = 1; i < len; ++i) {
    int j;
    for (j = 0; j < tail; ++j) {
      if (str[i] == str[j]) break;
    }
    if (j == tail) {
      str[tail] = str[i];
      ++tail;
    }
  }
  str[tail] = 0;
}

【问题讨论】:

  • 这是《破解代码面试》一书第 97 页中的练习之一。“编写代码以删除字符串中的重复字符不使用任何额外的缓冲区”。注意:一两个附加变量就可以了。没有额外的数组副本。
  • @FranklinDattein 你能建议一下吗,为什么这段代码返回:abbab 输入:aabbab?

标签: java string


【解决方案1】:

该功能对我来说看起来不错。我已经写了内联 cmets。希望对您有所帮助:

// function takes a char array as input.
// modifies it to remove duplicates and adds a 0 to mark the end
// of the unique chars in the array.
public static void removeDuplicates(char[] str) {
  if (str == null) return; // if the array does not exist..nothing to do return.
  int len = str.length; // get the array length.
  if (len < 2) return; // if its less than 2..can't have duplicates..return.
  int tail = 1; // number of unique char in the array.
  // start at 2nd char and go till the end of the array.
  for (int i = 1; i < len; ++i) { 
    int j;
    // for every char in outer loop check if that char is already seen.
    // char in [0,tail) are all unique.
    for (j = 0; j < tail; ++j) {
      if (str[i] == str[j]) break; // break if we find duplicate.
    }
    // if j reachs tail..we did not break, which implies this char at pos i
    // is not a duplicate. So we need to add it our "unique char list"
    // we add it to the end, that is at pos tail.
    if (j == tail) {
      str[tail] = str[i]; // add
      ++tail; // increment tail...[0,tail) is still "unique char list"
    }
  }
  str[tail] = 0; // add a 0 at the end to mark the end of the unique char.
}

【讨论】:

  • 代码不行;如果没有任何欺骗,最后一行会导致 ArrayIndexOutOfBoundsException。
  • @polygenelubricants:很好。
  • 为时已晚,但最后一个括号前的最后一行:[if(tail
  • @codaddict 谢谢。但是为什么我们最后要加一个 0 呢?它有什么特殊意义吗?或者我们假设 0 是分隔符?什么是传入的 Sting 是“aa0bcedef00”?那就是其中包含 0(零)?
  • @Ayusman ,0 和 '0' 是有区别的。见asciitable.com。 0 是(null),ASCII 码 = 0,'0' 是 '0',ASCII 码 = 48。运行以下程序查看区别:public static void main(String[] args) { char c = '0'; int x = c; System.out.println(c); System.out.println(x); c = 0; x = c; System.out.println(c); System.out.println(x); }
【解决方案2】:

很抱歉,您的代码非常类似于 C。

Java String 不是 char[]。您说您想从 String 中删除重复项,但您改为使用 char[]。

这是char[]\0-终止了吗?看起来不像,因为您采用了整个数组的 .length。但是随后您的算法会尝试\0-终止数组的一部分。如果数组不包含重复项会怎样?

好吧,正如它所写的那样,您的代码实际上在最后一行抛出了ArrayIndexOutOfBoundsException! \0 没有空间了,因为所有的插槽都用完了!

在这种特殊情况下,您可以添加一个检查以不添加\0,但是您打算如何使用此代码呢?您是否打算使用类似strlen 的函数来查找数组中的第一个\0?如果没有会发生什么? (由于上述所有独特的例外情况?)。

如果原始String/char[] 包含\0,会发生什么情况? (顺便说一句,这在 Java 中是完全合法的,请参阅 JLS 10.9 An Array of Characters is Not a String)

结果将是一团糟,这一切都是因为您想像 C 一样做所有事情,并且在没有任何额外缓冲区的情况下就位。你确定你真的需要这样做吗?为什么不使用String、indexOf、lastIndexOf、replace 以及String 的所有更高级别的API?是不是太慢了,还是你只是怀疑它太慢了?

“过早的优化是万恶之源”。很抱歉,如果您甚至无法理解原始代码的作用,那么弄清楚它如何适应更大(更混乱)的系统将是一场噩梦。


我的最低建议是执行以下操作:

  • 使函数接受并返回一个String,即public static String removeDuplicates(String in)
  • 在内部,使用char[] str = in.toCharArray();
  • 将最后一行替换为return new String(str, 0, tail);

这确实使用了额外的缓冲区,但至少与系统其余部分的接口更加干净。


或者,您也可以使用StringBuilder:

static String removeDuplicates(String s) {
    StringBuilder noDupes = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
        String si = s.substring(i, i + 1);
        if (noDupes.indexOf(si) == -1) {
            noDupes.append(si);
        }
    }
    return noDupes.toString();
}

请注意,这与您的算法本质上是相同的,但更简洁,没有那么多小角落等情况。

【讨论】:

  • 使用 StringBuilder 的解决方案当然更好,但不在问题的范围内。设计一种算法并编写代码以在不使用任何额外缓冲区的情况下删除字符串中的重复字符。注意:一两个附加变量就可以了。没有额外的数组副本。
  • @polygene 为什么在可以使用 charAt() 的情况下使用 substring()?
  • @DhruvGairola,我同意你的看法。这是一个合理的算法,但从风格的角度来看,如果使用charAt(i),这种方法将变得更具可读性。我喜欢看代码,就好像我把它交给从未见过它的人一样,我希望他们问的问题最少。
【解决方案3】:

鉴于以下问题:

编写代码以删除字符串中的重复字符 使用任何额外的缓冲区。注意:一个或两个附加变量 很好。数组的额外副本不是。

由于可以添加一两个额外变量,但不允许使用缓冲区,因此您可以通过使用整数来存储位来模拟哈希图的行为。这个简单的解决方案以 O(n) 运行,比你的要快。此外,它在概念上并不复杂且就地:

    public static void removeDuplicates(char[] str) {
        int map = 0;
        for (int i = 0; i < str.length; i++) {
            if ((map & (1 << (str[i] - 'a'))) > 0) // duplicate detected
                str[i] = 0;
            else // add unique char as a bit '1' to the map
                map |= 1 << (str[i] - 'a');
        }
    }

缺点是重复项(被 0 替换)不会放在 str[] 数组的末尾。但是,这可以通过最后一次遍历数组来轻松解决。此外,整数只能容纳普通字母。

【讨论】:

  • 我非常喜欢这个解决方案,非常喜欢 C。从概念上讲,这是一个很好的解决方案,但是,它不适用于正常情况。它只适用于 a..z 区分大小写。不支持空格。这将在 256 位系统中创造奇迹来处理整个 ASCII 范围。但它确实在 O(N) 中运行。我仍然 +1 这个。
  • @Dhruv:你能解释一下这个条件是如何工作的吗?- if ((map & (1 0)
  • @Dhruv 你为什么使用 str[i] - 'a' 以及 map 之后的符号是什么 - map |
  • 即使这种用法有明显的限制,我还是很喜欢这个解决方案之外的想法。类似于 C 语言,但具有指导意义。
【解决方案4】:
private static String removeDuplicateCharactersFromWord(String word) {

    String result = new String("");

    for (int i = 0; i < word.length(); i++) {
        if (!result.contains("" + word.charAt(i))) {
            result += "" + word.charAt(i);
        }
    }

    return result;
}

【讨论】:

  • 好招!使用“”将字符转换为字符串! +1 :) 你知道我们什么时候要打印一个'''',我们应该在打印命令中放什么吗?
  • 虽然这段代码看起来“干净”,但事实并非如此。如果单词太长,这个包含方法和字符串连接是你可能永远不会意识到的问题。
【解决方案5】:

这是我的解决方案。

算法与本练习出处的《Cracking the code interview》一书中的算法基本相同,但我尝试对其进行了一些改进,使代码更易于理解:

public static void removeDuplicates(char[] str) {
        // if string has less than 2 characters, it can't contain
        // duplicate values, so there's nothing to do
        if (str == null || str.length < 2) {
            return;
        }

        // variable which indicates the end of the part of the string 
        // which is 'cleaned' (all duplicates removed)
        int tail = 0;

        for (int i = 0; i < str.length; i++) {
            boolean found = false;
            
            // check if character is already present in
            // the part of the array before the current char
            for (int j = 0; j < i; j++) {
                if (str[j] == str[i]) {
                    found = true;
                    break;
                }
            }

            // if char is already present
            // skip this one and do not copy it
            if (found) {
                continue;
            }

            // copy the current char to the index 
            // after the last known unique char in the array
            str[tail] = str[i];
            tail++;
        }
                          
        str[tail] = '\0';
    }

本书的一个重要要求是就地(如我的解决方案),这意味着在处理字符串时不应使用额外的数据结构作为帮助器。这样可以避免不必要地浪费内存,从而提高性能。

【讨论】:

  • +1 恕我直言,这里共享的更智能、更易于理解的解决方案严格满足以下要求:就地执行(我理解为:不使用高级框架函数,也不使用大辅助结构可能比原始字符串大)。这是一个面试/教学式的问题,因此应该是解决方案。
【解决方案6】:
char[] chars = s.toCharArray();
    HashSet<Character> charz = new HashSet<Character>();

    for(Character c : s.toCharArray() )
    {
        if(!charz.contains(c))
        {
            charz.add(c);
            //System.out.print(c);
        }
    }

    for(Character c : charz)
    {
        System.out.print(c);
    }

【讨论】:

  • 您需要使用 LinkedHashSet 来维护原始字符串中的字符顺序。此外,如果您使用的是 Set,则不需要 contains 子句。
【解决方案7】:
public String removeDuplicateChar(String nonUniqueString) {
    String uniqueString = "";
    for (char currentChar : nonUniqueString.toCharArray()) {
        if (!uniqueString.contains("" + currentChar)) {
            uniqueString += currentChar;
        }
    }

    return uniqueString;
}

【讨论】:

  • 您能在这个答案中添加一些文字吗?我们通常不会简单地发送代码转储,而是尝试解释代码的逻辑:)
  • 这实际上是一个绝妙的解决方案!该代码本质上是尝试将字符串转换为字符数组,并利用 String 类的 'contains' 方法来检查字符(以字符串的形式)是否存在于 'rs' 中。
【解决方案8】:
public static void main (String [] args)
    {
        String s = "aabbbeeddsfre";//sample string
        String temp2="";//string with no duplicates
        HashMap<Integer,Character> tc = new HashMap<Integer,Character>();//create a hashmap to store the char's
        char [] charArray = s.toCharArray();
        for (Character c : charArray)//for each char
        {
            if (!tc.containsValue(c))//if the char is not already in the hashmap
                {
                    temp2=temp2+c.toString();//add the char to the output string
                    tc.put(c.hashCode(),c);//and add the char to the hashmap
                }
        }

        System.out.println(temp2);//final string
    }

我认为我们也可以使用 Set 来代替 HashMap。

【讨论】:

    【解决方案9】:

    我知道这是一个 Java 问题,但因为我有一个很好的解决方案,可以激发人们将其转换为 Java,无论如何。我也喜欢针对常见问题提供多种语言提交的答案。

    所以这里有一个 Python 解决方案,它是 O(n) 并且还支持整个 ASCII 范围。当然它不会将'a'和'A'视为相同:

    我使用 8 x 32 位作为哈希图:

    输入也是一个使用dedup(list('some string'))的字符串数组

    def dedup(str):
        map = [0,0,0,0,0,0,0,0]
        for i in range(len(str)):
            ascii = ord(str[i])
            slot = ascii / 32
            bit = ascii % 32
            bitOn = map[slot] & (1 << bit)
            if bitOn:
                str[i] = ''
            else:
                map[slot] |= 1 << bit
    
        return ''.join(str)
    

    还有一种更pythonian的方法是使用集合:

    def dedup(s):
        return ''.join(list(set(s)))
    

    【讨论】:

    • 我喜欢你节省内存的方式。但是你怎么能做 str[i] = '' ?字符串在 python 中不是不可变的吗?
    【解决方案10】:

    子串方法。使用.concat() 完成连接以避免为+ 的左手和右手分配额外的内存。 注意:这甚至会删除重复的空格。

    private static String withoutDuplicatesSubstringing(String s){
    
            for(int i = 0; i < s.length(); i++){
              String sub = s.substring(i+1);
              int index = -1;
              while((index = sub.toLowerCase().indexOf(Character.toLowerCase(s.charAt(i)))) > -1 && !sub.isEmpty()){
                  sub = sub.substring(0, index).concat(sub.substring(index+1, sub.length()));
              }
              s = s.substring(0, i+1).concat(sub);
            }
            return s;
        }
    

    测试用例:

    String testCase1 = "nanananaa! baaaaatmaan! batman!";

    输出: na! btm

    【讨论】:

      【解决方案11】:

      问题:删除字符串中的重复字符 方法一:(Python)

      import collections
      
      a = "GiniGinaProtijayi"
      
      aa = collections.OrderedDict().fromkeys(a)
      print(''.join(aa))
      

      方法二:(Python)

      a = "GiniGinaProtijayi"
      list = []
      aa = [ list.append(ch) for ch in a if  ch  not in list]
      print( ''.join(list))
      

      在 Java 中:

      class test2{
          public static void main(String[] args) {
      
       String a = "GiniGinaProtijayi";
       List<Character> list = new ArrayList<>();
      
             for(int i = 0 ; i < a.length() ;i++) {
                 char ch = a.charAt(i);
                 if( list.size() == 0 ) {list.add(ch);}
                 if(!list.contains(ch)) {list.add(ch) ;}
      
             }//for
             StringBuffer sbr = new StringBuffer();
      
            for( char ch : list) {sbr.append(ch);}
            System.out.println(sbr);
      
          }//main
      
      }//end
      

      【讨论】:

        【解决方案12】:

        如果您只是循环遍历数组并将所有新字符添加到列表中,然后重新排列该列表,这会容易得多。

        使用这种方法,您需要在遍历数组时重新排列数组,并最终将其重新调整为适当的大小。

        【讨论】:

        • 感谢 ck,但我正在尝试在不使用任何额外缓冲区的情况下就地执行代码。
        【解决方案13】:
            String s = "Javajk";
            List<Character> charz = new ArrayList<Character>();
            for (Character c : s.toCharArray()) {
                if (!(charz.contains(Character.toUpperCase(c)) || charz
                        .contains(Character.toLowerCase(c)))) {
                    charz.add(c);
                }
            }
             ListIterator litr = charz.listIterator();
           while (litr.hasNext()) {
        
               Object element = litr.next();
               System.err.println(":" + element);
        
           }    }
        

        如果字符在两种情况下都存在,这将删除重复项。

        【讨论】:

          【解决方案14】:
          public class RemoveDuplicateInString {
              public static void main(String[] args) {
                  String s = "ABCDDCA";
                  RemoveDuplicateInString rs = new RemoveDuplicateInString();
                  System.out.println(rs.removeDuplicate(s));
          
              }
          
              public String removeDuplicate(String s) {
                  String retn = null;
                  boolean[] b = new boolean[256];
          
                  char[] ch = s.toCharArray();
                  for (int i = 0; i < ch.length; i++) {
          
                      if (b[ch[i]]) {
                          ch[i]=' ';
          
                      }
          
                      else {
                          b[ch[i]] = true;
          
                      }
                  }
          
                  retn = new String(ch);
                  return retn;
          
              }
          
          }
          

          【讨论】:

            【解决方案15】:
            /* program to remove the duplicate character in string */
            /* Author senthilkumar M*/
            
            char *dup_remove(char *str) 
            {
                int i = 0, j = 0, l = strlen(str);
                int flag = 0, result = 0;
            
                for(i = 0; i < l; i++) {
                     result = str[i] - 'a';
                     if(flag & (1 << result)) {
                        */* if duplicate found remove & shift the array*/*
                        for(j = i; j < l; j++) {
                              str[j] = str[j+1];
                         }
                         i--; 
                         l--; /* duplicates removed so string length reduced by 1 character*/
                         continue;
                     }
                     flag |= (1 << result);
                 }
                 return str;
            }
            

            【讨论】:

              【解决方案16】:
              public class RemoveCharsFromString {
              
              static String testcase1 = "No, I am going to Noida";
              static String testcase2 = "goings";
              
              public static void main(String args[])throws StringIndexOutOfBoundsException{
                  RemoveCharsFromString testInstance= new RemoveCharsFromString();
                  String result = testInstance.remove(testcase1,testcase2);
                  System.out.println(result);
              }
              
              //write your code here
              public String remove(String str, String str1)throws StringIndexOutOfBoundsException
                  {   String result=null;
              
              
                     if (str == null)
                      return "";
              
              
                  try
                  {
                   for (int i = 0; i < str1.length (); i++) 
                  {
              
              
                      char ch1=str1.charAt(i);
                      for(int j=0;j<str.length();j++)
                      {
                          char ch = str.charAt (j);
              
                      if (ch == ch1)
                      {
                      String s4=String.valueOf(ch);
                      String s5= str.replaceAll(s4, "");
                      str=s5;
              
              
                      }
                      }
              
                  }
                  }
                  catch(Exception e)
                  {
              
                  }
                  result=str;
                  return result;
                  }
               }
              

              【讨论】:

                【解决方案17】:
                public static void main(String[] args) {
                
                    char[] str = { 'a', 'b', 'a','b','c','e','c' };
                
                    for (int i = 1; i < str.length; i++) {
                        for (int j = 0; j < i; j++) {
                            if (str[i] == str[j]) {
                                str[i] = ' ';
                            }
                        }
                
                    }
                    System.out.println(str);
                }
                

                【讨论】:

                  【解决方案18】:

                  使用位掩码处理 256 个字符的改进版本:

                  public static void removeDuplicates3(char[] str) 
                  {
                    long map[] = new long[] {0, 0, 0 ,0};
                    long one = 1;
                  
                    for (int i = 0; i < str.length; i++) 
                    {
                      long chBit = (one << (str[i]%64));
                      int n = (int) str[i]/64;
                  
                      if ((map[n] & chBit ) > 0) // duplicate detected
                          str[i] = 0;
                      else // add unique char as a bit '1' to the map
                          map[n] |= chBit ;
                    }
                  
                    // get rid of those '\0's
                    int wi = 1;
                    for (int i=1; i<str.length; i++)
                    {
                      if (str[i]!=0) str[wi++] = str[i];
                    }
                  
                    // setting the rest as '\0'
                    for (;wi<str.length; wi++) str[wi] = 0;
                  }
                  

                  结果:"##1!!ASDJasanwAaw.,;..][,[]==--0" ==> "#1!ASDJasnw.,;][=-0" (不包括双引号)

                  【讨论】:

                    【解决方案19】:

                    此函数从字符串内联中删除重复项。我使用 C# 作为编码语言,并且内联删除了重复项

                     public static void removeDuplicate(char[] inpStr)
                            {
                                if (inpStr == null) return;
                                if (inpStr.Length < 2) return;
                    
                            for (int i = 0; i < inpStr.Length; ++i)
                            {
                    
                                int j, k;
                                for (j = 1; j < inpStr.Length; j++)
                                {
                    
                                    if (inpStr[i] == inpStr[j] && i != j)
                                    {
                                        for (k = j; k < inpStr.Length - 1; k++)
                                        {
                                            inpStr[k] = inpStr[k + 1];
                                        }
                                        inpStr[k] = ' ';
                                    }
                                }
                    
                            }
                    
                    
                            Console.WriteLine(inpStr);
                    
                        }
                    

                    【讨论】:

                      【解决方案20】:

                      (Java) 避免使用 Map、List 数据结构:

                      private String getUniqueStr(String someStr) {
                          StringBuilder uniqueStr = new StringBuilder();
                                  if(someStr != null) {
                             for(int i=0; i <someStr.length(); i++)   {
                              if(uniqueStr.indexOf(String.valueOf(someStr.charAt(i))) == -1)  {
                                  uniqueStr.append(someStr.charAt(i));
                              }
                             }
                                  }
                          return uniqueStr.toString();
                      }
                      

                      【讨论】:

                        【解决方案21】:
                        package com.java.exercise;
                        
                        public class RemoveCharacter {
                        
                            /**
                             * @param args
                             */
                            public static void main(String[] args) {
                                RemoveCharacter rem = new RemoveCharacter();
                                char[] ch=rem.GetDuplicates("JavavNNNNNNC".toCharArray());
                                char[] desiredString="JavavNNNNNNC".toCharArray();
                                System.out.println(rem.RemoveDuplicates(desiredString, ch));
                        
                            }
                            char[] GetDuplicates(char[] input)
                            {
                                int ctr=0;
                                char[] charDupl=new char[20];
                                for (int i = 0; i <input.length; i++)
                                {
                                    char tem=input[i];
                                    for (int j= 0; j < i; j++)
                                    {
                                        if (tem == input[j])
                                        {
                                            charDupl[ctr++] = input[j];
                                        }
                        
                                    }
                                }
                        
                        
                                return charDupl;
                            }
                             public char[] RemoveDuplicates(char[] input1, char []input2)
                             {
                        
                                 int coutn =0;
                                 char[] out2 = new char[10];
                                 boolean flag = false;
                                 for (int i = 0; i < input1.length; i++)
                                 {
                                     for (int j = 0; j < input2.length; j++)
                                     {
                        
                                             if (input1[i] == input2[j])
                                             {
                                                 flag = false;
                                                 break;
                                             }
                                             else
                                             {
                                                 flag = true;
                                             }
                        
                                     }
                                     if (flag)
                                     {
                                         out2[coutn++]=input1[i];
                                         flag = false;
                                     }
                                 }
                                 return out2;
                             }
                        }
                        

                        【讨论】:

                          【解决方案22】:

                          另一个解决方案,似乎是迄今为止最简洁的:

                          private static String removeDuplicates(String s)
                              {   
                                  String x = new String(s);
                          
                                  for(int i=0;i<x.length()-1;i++)
                                      x = x.substring(0,i+1) + (x.substring(i+1)).replace(String.valueOf(x.charAt(i)), "");
                          
                                  return x;
                              }   
                          

                          【讨论】:

                            【解决方案23】:

                            我写了一段代码来解决这个问题。 我检查了某些值,得到了所需的输出。

                            注意:这很耗时。

                            static void removeDuplicate(String s) {
                            
                                char s1[] = s.toCharArray();
                            
                                Arrays.sort(s1);                    //Sorting is performed, a to z
                                            //Since adjacent values are compared
                            
                                int myLength = s1.length;           //Length of the character array is stored here
                            
                                int i = 0;                          //i refers to the position of original char array
                                int j = 0;          //j refers to the position of char array after skipping the duplicate values 
                            
                                while(i != myLength-1 ){
                            
                                    if(s1[i]!=s1[i+1]){     //Compares two adjacent characters, if they are not the same
                                        s1[j] = s1[i];      //if not same, then, first adjacent character is stored in s[j]
                                        s1[j+1] = s1[i+1];  //Second adjacent character is stored in s[j+1]
                                        j++;                //j is incremented to move to next location
                                    }
                            
                                    i++;                    //i is incremented
                                }
                            
                                //the length of s is i. i>j
                            
                                String s4 = new String (s1);        //Char Array to String
                            
                                //s4[0] to s4[j+1] contains the length characters after removing the duplicate
                                //s4[j+2] to s4[i] contains the last set of characters of the original char array
                            
                                System.out.println(s4.substring(0, j+1));
                            
                            }
                            

                            随意使用您的输入运行我的代码。谢谢。

                            【讨论】:

                              【解决方案24】:
                              public class RemoveRepeatedCharacters {
                              
                                  /**
                                   * This method removes duplicates in a given string in one single pass.
                                   * Keeping two indexes, go through all the elements and as long as subsequent characters match, keep
                                   * moving the indexes in opposite directions. When subsequent characters don't match, copy value at higher index
                                   * to (lower + 1) index.
                                   * Time Complexity = O(n)
                                   * Space  = O(1)
                                   * 
                                   */
                                  public static void removeDuplicateChars(String text) {
                              
                                      char[] ch = text.toCharArray();
                                      int i = 0; //first index
                                      for(int j = 1; j < ch.length; j++) {
                                          while(i >= 0 && j < ch.length && ch[i] == ch[j]) {
                                              i--;
                                              j++;
                                              System.out.println("i = " + i + " j = " + j);               
                              
                                          }
                              
                                          if(j < ch.length) {
                                              ch[++i] = ch[j];
                                          }
                              
                                      }
                              
                                      //Print the final string
                                      for(int k = 0; k <= i; k++)
                                          System.out.print(ch[k]);
                              
                                  }
                              
                                  public static void main(String[] args) {
                              
                                      String text = "abccbdeefgg";
                                      removeDuplicateChars(text);
                              
                                  }
                              
                              }
                              

                              【讨论】:

                              • 不知道为什么你决定发布这个方法,因为过去有其他方法与你的方法相似。
                              【解决方案25】:
                              public class StringRedundantChars {
                                  /**
                                   * @param args
                                   */
                                  public static void main(String[] args) {
                              
                                      //initializing the string to be sorted
                                      String sent = "I love painting and badminton";
                              
                                      //Translating the sentence into an array of characters
                                      char[] chars = sent.toCharArray();
                              
                                      System.out.println("Before Sorting");
                                      showLetters(chars);
                              
                                      //Sorting the characters based on the ASCI character code. 
                                      java.util.Arrays.sort(chars);
                              
                                      System.out.println("Post Sorting");
                                      showLetters(chars);
                              
                                      System.out.println("Removing Duplicates");
                                      stripDuplicateLetters(chars);
                              
                                      System.out.println("Post Removing Duplicates");
                                      //Sorting to collect all unique characters 
                                      java.util.Arrays.sort(chars);
                                      showLetters(chars);
                              
                                  }
                              
                                  /**
                                   * This function prints all valid characters in a given array, except empty values
                                   * 
                                   * @param chars Input set of characters to be displayed
                                   */
                                  private static void showLetters(char[] chars) {
                              
                                      int i = 0;
                                      //The following loop is to ignore all white spaces
                                      while ('\0' == chars[i]) {
                                          i++;
                                      }
                                      for (; i < chars.length; i++) {
                                          System.out.print(" " + chars[i]);
                                      }
                                      System.out.println();
                                  }
                              
                                  private static char[] stripDuplicateLetters(char[] chars) {
                              
                                      // Basic cursor that is used to traverse through the unique-characters
                                      int cursor = 0;
                                      // Probe which is used to traverse the string for redundant characters
                                      int probe = 1;
                              
                                      for (; cursor < chars.length - 1;) {
                              
                                          // Checking if the cursor and probe indices contain the same
                                          // characters
                                          if (chars[cursor] == chars[probe]) {
                                              System.out.println("Removing char : " + chars[probe]);
                                              // Please feel free to replace the redundant character with
                                              // character. I have used '\0'
                                              chars[probe] = '\0';
                                              // Pushing the probe to the next character
                                              probe++;
                                          } else {
                                              // Since the probe has traversed the chars from cursor it means
                                              // that there were no unique characters till probe.
                                              // Hence set cursor to the probe value
                                              cursor = probe;
                                              // Push the probe to refer to the next character
                                              probe++;
                                          }
                                      }
                                      System.out.println();
                              
                                      return chars;
                                  }
                              }
                              

                              【讨论】:

                              • @Shrivatsan:欢迎来到 stackover 流程​​。你提出了一个很老的问题。它也有一个很好的答案。您可以添加新的答案,但包括更具体的细节,您的答案与其他人相比如何......比如内存/时间复杂度等。
                              【解决方案26】:

                              这是我的解决方案

                              public static String removeDup(String inputString){
                                  if (inputString.length()<2) return inputString;
                                  if (inputString==null) return null;
                                  char[] inputBuffer=inputString.toCharArray();
                                  for (int i=0;i<inputBuffer.length;i++){
                                      for (int j=i+1;j<inputBuffer.length;j++){
                                          if (inputBuffer[i]==inputBuffer[j]){
                                              inputBuffer[j]=0;
                                          }
                                      }
                                  }
                                  String result=new String(inputBuffer);
                                  return result;
                              }
                              

                              【讨论】:

                                【解决方案27】:

                                我想出了以下解决方案。 请记住, S 和 s 不是重复的。我也只有一个硬编码值。但代码工作得很好。

                                public static String removeDuplicate(String str) {

                                    StringBuffer rev = new StringBuffer();  
                                    rev.append(str.charAt(0));
                                
                                    for(int i=0; i< str.length(); i++)
                                    {
                                        int flag = 0;
                                        for(int j=0; j < rev.length(); j++)
                                        {
                                            if(str.charAt(i) == rev.charAt(j))
                                            {
                                                flag = 0;
                                                break;
                                            }
                                            else
                                            {
                                                flag = 1;
                                            }
                                        }
                                        if(flag == 1)
                                        {
                                            rev.append(str.charAt(i));
                                        }
                                    }
                                
                                    return rev.toString();
                                }
                                

                                【讨论】:

                                  【解决方案28】:

                                  我无法理解解决方案背后的逻辑,所以我编写了简单的解决方案:

                                    public static void removeDuplicates(char[] str) {
                                  
                                      if (str == null) return; //If the string is null return      
                                      int length = str.length; //Getting the length of the string
                                      if (length < 2) return; //Return if the length is 1 or smaller
                                  
                                      for(int i=0; i<length; i++){ //Loop through letters on the array
                                  
                                          int j;
                                  
                                          for(j=i+1;j<length;j++){ //Loop through letters after the checked letters (i) 
                                  
                                              if (str[j]==str[i]){ //If you find duplicates set it to 0
                                  
                                                  str[j]=0;
                                              }
                                          }
                                      }
                                  }
                                  

                                  【讨论】:

                                    【解决方案29】:

                                    使用番石榴你可以做类似Sets.newHashSet(charArray).toArray(); 如果您没有使用任何库,您仍然可以使用 new HashSet&lt;Char&gt;() 并在那里添加您的 char 数组。

                                    【讨论】:

                                      【解决方案30】:
                                      #include <iostream>
                                      #include <string>
                                      using namespace std;
                                      
                                      int main() {
                                          // your code goes here
                                          string str;
                                          cin >> str;
                                          long map = 0;
                                          for(int  i =0; i < str.length() ; i++){
                                              if((map & (1L << str[i])) > 0){
                                                  str[i] = 0;
                                              }
                                              else{
                                                  map |= 1L << str[i];
                                              }
                                          }
                                          cout << str;
                                          return 0;
                                      }
                                      

                                      【讨论】:

                                        猜你喜欢
                                        • 2012-05-09
                                        • 2013-11-12
                                        • 1970-01-01
                                        • 1970-01-01
                                        • 2020-03-30
                                        • 1970-01-01
                                        • 2018-07-19
                                        • 2012-04-08
                                        • 1970-01-01
                                        相关资源
                                        最近更新 更多