用于删除字符串中重复字符的函数

时间:2010-04-08 07:06:56

标签: java string

以下代码尝试删除字符串中的任何重复字符。我不确定代码是否正确。任何人都可以帮我处理代码(即当字符匹配时实际发生了什么)?

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;
}

34 个答案:

答案 0 :(得分:43)

这个功能对我来说很好看。我写过内联评论。希望它有所帮助:

// 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.
}

答案 1 :(得分:33)

你的代码是,我很遗憾地说,非常像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的事情,而且没有任何额外的缓冲区。你确定你真的需要这样做吗?为什么不使用StringindexOflastIndexOfreplace以及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();
}

请注意,这与您所拥有的算法基本相同,但更清晰,没有太少的小角落等等。

答案 2 :(得分:17)

鉴于以下问题:

  

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

由于一个或两个附加变量很好但不允许缓冲区,因此可以使用整数来存储位来模拟散列映射的行为。这个简单的解决方案运行在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 []数组的末尾。但是,这可以通过最后一次循环遍历数组来轻松解决。此外,整数只能容纳常规字母。

答案 3 :(得分:11)

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;
}

答案 4 :(得分:6)

这是我对O(n ^ 2)复杂度问题的解决方案。这个想法与书中的想法大致相同,但我相信我的解决方案更易读,更容易理解算法本身:

private static void removeDuplicates(char[] str) {
        if (str == null || str.length < 2) {
            return;
        }

        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';
    }

答案 5 :(得分:4)

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);
    }

答案 6 :(得分:3)

public String removeDuplicateChar(String nonUniqueString) {
    String uniqueString = "";
    for (char currentChar : nonUniqueString.toCharArray()) {
        if (!uniqueString.contains("" + currentChar)) {
            uniqueString += currentChar;
        }
    }

    return uniqueString;
}

答案 7 :(得分:2)

子串方法。使用.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

答案 8 :(得分:2)

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

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

我使用8 x 32位作为hashmap:

另外输入是使用重复数据删除的字符串数组(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)

另一种更加蟒蛇化的方法是使用集合:

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

答案 9 :(得分:2)

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
    }

而不是HashMap我想我们也可以使用Set。

答案 10 :(得分:0)

到目前为止,另一种解决方案似乎是最简洁的:

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;
    }   

答案 11 :(得分:0)

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

import collections

a = "GiniGinaProtijayi"

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

方法2:(Python)

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

IN 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 :(得分:0)

resolve这本书的类似练习:破解编码面试 使用递归。

package crackingcodeinterview;

public class Exercise {

static String textString = "this is a random text of example!@#$%^(^452464156";

public static void main(String[] args) {

    filterLetters(0, "");
}

public static void filterLetters(int position, String letters) {
    if (position != textString.length()) {

        boolean p = false;

        for (int i = 0; i < letters.length(); i++) {
            if (letters.charAt(i) == textString.charAt(position)) {
                p = true;
                break;
            }
        }

        if (!p) {
            letters += textString.charAt(position);
        }
        position++;
        filterLetters(position, letters);
    } else {
        System.out.println(letters);
    }
  }
}

使用子字符串和递归的其他solution

public class MyClass {
public static void main(String args[]) {

    getUnicLetter("esta es una cadena con letras repetidas","");
}



   public static String getUnicLetter(String originalWord,String finalWord){
        if(originalWord.isEmpty()) return  null;
        System.out.print(finalWord);
        return getUnicLetter(originalWord.replace(originalWord.substring(0,1),""),finalWord.contains(originalWord.substring(0,1)) ? "" : originalWord.substring(0,1));
    }

}

答案 13 :(得分:0)

O(n)解决方案:

import java.util.*;
import java.io.*;

public class String_Duplicate_Removal
{

public static String duplicate_removal(String s)
    {
        if(s.length()<2)
            return s;

        else if(s.length()==2)
        {
            if(s.charAt(0)==s.charAt(1))
                s = Character.toString(s.charAt(0));
            return s;
        }

        boolean [] arr = new boolean[26];

        for(int i=0;i<s.length();i++)
        {

            if(arr[s.charAt(i)-'a']==false)
                arr[s.charAt(i)-'a']=true;

            else
            {
                s= ((new StringBuilder(s)).deleteCharAt(i)).toString();
                i--;
            }
        }
        return s;
    }   

    public static void main(String [] args)
    {
        String s = "abbashbhqa";
        System.out.println(duplicate_removal(s));
    }
}

答案 14 :(得分:0)

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

  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;
            }
        }
    }
}

答案 15 :(得分:0)

我想出了以下解决方案。 请记住,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();
}

答案 16 :(得分:0)

这是我的解决方案

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;
}

答案 17 :(得分:0)

    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);

   }    }

如果两个案例中都存在该字符,则会删除副本。

答案 18 :(得分:0)

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;
    }
}

答案 19 :(得分:0)

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

注意:这很费时间。

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));

}

随意输入我的代码。感谢。

答案 20 :(得分:0)

/* 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;
}

答案 21 :(得分:0)

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 :(得分:0)

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);

    }

}

答案 23 :(得分:0)

(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();
}

答案 24 :(得分:0)

此函数从字符串内联中删除重复项。我使用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);

    }

答案 25 :(得分:0)

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

使用这种方法,您需要在单步执行时重新洗牌,最后将其重新定位到适当的大小。

答案 26 :(得分:0)

使用位掩码处理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”==&gt; “#1!ASDJasnw。,;] [= - 0”(不包括双引号)

答案 27 :(得分:0)

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

答案 28 :(得分:0)

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);
}

答案 29 :(得分:0)

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;
    }
 }

答案 30 :(得分:0)

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;

    }

}

答案 31 :(得分:-1)

public static StringBuffer removeDuplicateCharsInPlace(StringBuffer sb)
{   
    if (sb==null|| sb.equals(""))
        return new StringBuffer("String empty or null.");

    if(sb.length()==1)
        return sb;

    // iterate through the entire string
    for (int i=0;i<sb.length();i++)
    {   
        //Save one character as string
        String subString = sb.substring(i, i+1);

        // Find the first index of the selected character
        int startIndex = sb.indexOf(subString);
        int nextIndex;

        do
        {   //find the next index of the selected character
            nextIndex = sb.indexOf(subString, startIndex + 1);

            // If found, delete the character
            if(nextIndex!=-1)
                sb.deleteCharAt(nextIndex);

            // Set the next start of the index to the last found index - 1 (minus one because a character has been deleted)
            startIndex=nextIndex-1;

        }while(nextIndex!=-1);  // Keep repeating until we keep finding repeated characters' indexes
    }
    return sb;
}

答案 32 :(得分:-1)

#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;
}

答案 33 :(得分:-2)

这将解决快速简单代码的目的。 它给出O(n)的结果。

void removeduplicate(char *str)
{
    int checker = 0;
    int cnt = 0;
    for(int i = 0; i < strlen(str); i++)
    {
        int val = *(str + i) - (int)'a';
        if ((checker & (1 << val)) > 0) continue;
        else {
            *(str + cnt) = *(str + i);
            cnt++;
        }
        checker |= (1 << val);
    }
    *(str+cnt) = '\0';
}