以递归方式从字符串中删除重复的字符

时间:2011-05-11 02:24:41

标签: java

我需要帮助来确定如何从字符串中删除重复字符。它必须以递归方式完成,这才是真正的问题。

public class FEQ2 {
    /**
     * @param args
     */
    public static void removeDups(String s, int firstChar, int secondChar) {    
        if (s.length() == 1) {  
            System.out.println(s);
        }           
        char a = s.charAt(firstChar);
        if (a == s.charAt(secondChar)) {
            s = a + s.substring(secondChar + 1);
        }
        System.out.println(s);
        removeDups(s, firstChar + 1, secondChar + 1);
        //return s;
    }

    public static void main(String[] args) {
        //System.out.println(removeDups("AAAABBARRRCC", 1));
        removeDups("AAAABBARRRCC", 0 , 1);
    }
}

6 个答案:

答案 0 :(得分:5)

你可以这样做:

public static String removeDups(String s)
{
    if ( s.length() <= 1 ) return s;
    if( s.substring(1,2).equals(s.substring(0,1)) ) return removeDups(s.substring(1));
    else return s.substring(0,1) + removeDups(s.substring(1));
}


INPUT: "AAAABBARRRCC"
OUTPUT: "ABARC"

===============

编辑:另一种方式

public static String removeDups(String s)
{
    if ( s.length() <= 1 ) return s;
    if( s.substring(1).contains(s.substring(0,1)) ) return removeDups(s.substring(1));
    else return s.substring(0,1) + removeDups(s.substring(1));
}


INPUT: "AAAABBARRRCC"
OUTPUT: "BARC"

==============

编辑:第三种方式

public static String removeDups(String s)
{
    if ( s.length() <= 1 ) return s;
    if( s.substring(0,s.length()-1).contains(s.substring(s.length()-1,s.length())) ) return removeDups(s.substring(0,s.length()-1));
    else return removeDups(s.substring(0,s.length()-1)) + s.substring(s.length()-1,s.length());
}


INPUT: "AAAABBARRRCC"
OUTPUT: "ABRC"

答案 1 :(得分:1)

递归操作的一般技巧是获取所有变量并将它们转换为参数,并将所有赋值更改为函数调用。对于更复杂的东西,您可能需要多个函数,但通常可以很容易地将每个循环转换为tail-recursive函数:

function(){
    int i=0; int x=0; //initialize 
    while(condition){
        x = x+i; //update
        i = i+1;
    }
    return x;
}

成为

function(i,x){ //variables are now parameters
    if(condition){
       return x;
    }else{
       return function(i+1, x+i); //update
    }
}

main(){
    function(0,0); //initialize

===============

这里有一些重复的删除代码,例如(它与你的完全不同)

removeDuplicates(str):
    i = str.length-1; out_str = ""; chars_used = []
    while(i >= 0):
        c = str[i]
        if(c not in chars_used):
            chars_used.append(c)
            out_str += c
        i -= 1
    return out_str

变为

remove_duplicates(str, i, out_str, chars_used):
    if i < 0:
        return out_str
    else:
        c = str[i]
        if c in chars_used:
            return remove_duplicates(str, i-1, out_str, chars_used)
        else:
            return remove_duplicates(str, i-1, out_str+c, chars_used+[c])

答案 2 :(得分:0)

这会对你有帮助吗?

    public static String getUniqueChars(String realString) {
        StringBuilder resultString = null;
        try {
                List<Character> characterArray = new <Character> ArrayList();
                for(char c : realString.toCharArray()) {
                    characterArray.add(c);
                }
                resultString = new StringBuilder();
                for(Character c : new TreeSet<Character>(characterArray)) {
                    resultString.append(c.charValue());
                }
        } catch (Exception e) {
                e.printStackTrace();
        }
        resultString.toString();
    }

答案 3 :(得分:0)

private static String removeChars(String s) {
    int n= s.length();
    int i= 0;
    int j= 1;
    Map<Integer, Boolean> mark= new HashMap<>();
    while(j<n) {
        if(s.charAt(i)== s.charAt(j)) {
            mark.put(i, true);
            mark.put(j, true);
            if(i== 0) {
                i= j+1;
                j= i+1;
            } else {
                i= i-1;
                j= j+1;
            }
        } else {
            i= j;
            j= j+1;
        }
    }

    String str= "";
    for(int k= 0;k<n;k++) {
        if(!mark.containsKey(k)) {
            str+= s.charAt(k);
        }
    }
    return str;
}

答案 4 :(得分:0)

我认为这更简单:

private static String removeDups(String input){
    if (input.length() <= 1) return input;
    if (input.charAt(0) == input.charAt(1))
        return removeDups(input.substring(1));
    else
        return input.charAt(0)+removeDups(input.substring(1));
}

答案 5 :(得分:0)

在C中:

/* @params:
* src  -- input string pointer. String to remove dups from.
* dest -- output string pointer. Passed in as empty string.  
* iter -- index from where duplicate removal starts. (0)
* ---------------------------------------------------------
* Purpose:  
* Removes duplicate characters from a string recursively. 
*/
void remove_Dups_recursively(char *src, char *dest, int iter){
  /* base case 1 --> empty or 1 letter string */
   if(strlen(src) <= 1){
       dest = src;
       return;
   }

  /* base case 2 --> reached end of string */
   if(iter == strlen(src)){
       return;
   }

  /* current 'iter' element has been encountered before */
   if(strchr(dest, src[iter]) == NULL){
       dest[strlen(dest)] = src[iter]; 
       iter++;
       remove_Dups_recursively(src, dest, iter);
   }

  /* current 'iter' element has not been encountered before */
   else{
       iter++;
       remove_Dups_recursively(src, dest, iter);
   }
}
/* EXAMPLE: AAABBABCCABA
 * OUTPUT: ABC    */