4

I need help to figure how can i remove duplicates chars from a string. It has to be done recursively which is the real problem..

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);
    }
}
2
  • Is this from a homework? If so, could you copy the exact question? Commented May 11, 2011 at 2:48
  • And can you say what would be the expected result? ABARC or ABRC? If it is homework - are there restrictions, what to use and what not? Commented May 11, 2011 at 3:20

7 Answers 7

5

You can do it like this:

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"

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

EDIT: another way

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"

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

EDIT: 3rd way

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"
Sign up to request clarification or add additional context in comments.

4 Comments

Is it wise to provide solution to homework question? What will they learn?
Does not work for -> "azxxzy" which should give -> "ay"
@BigShow, the solutions do not "completely" remove the duplicates, they keep each character but remove duplicates rather. Therefore, the output of your string azxxzy is azxy.
Your second and third approach gives different result for some string like: input- abcabdfcfreb output- erfabdfc || f is repeating what am I doing wrong here? Please correct me.
2

The general trick on doing things recursively is to take all variables and turn them into parameters, and change all assignments into function calls. You might need more than one function for the more complicated stuff, but usually you can turn each loop into a tail-recursive function quite easily:

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

becomes

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

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

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

Here is some duplicate removing code, just for example (it doesn´t do the same thing as yours though)

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

becomes

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

Comments

0

Will this help you?

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

Comments

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

Comments

0

I think this is simpler:

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

Comments

0

in 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    */

Comments

0

In case this helps somebody...

public static String cleanDuplicateAdjacentChars(String string) {
    // STOPPER: String is 1 or 0 chars
    if(string.length() <= 1) return string;
    // If first char equals second char then return recursive of string minus first char
    if(string.charAt(0) == string.charAt(1)) return clearEqualChars(string.substring(1));
    // Else return first char + recursive of string minus first char
    return string.charAt(0) + clearEqualChars(string.substring(1));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.