-6

Language : Java Key Notes: *Needs to loop through a String using either a For loop or While loop *It removes the duplicate letter(s) of the String and returns the word without the dupilcates.

Eg: The string is HELLO - The method then loops through and removes any duplicates, in this case " L " and returns in the end HELO

i have this so far

private String removeAnyDuplicates(String userWord)
{
   //Code goes here?
   return "" ; // Need to return the new string
}
4
  • 9
    Always share the code you have tried as part of your question. Commented Aug 25, 2013 at 5:46
  • Welcome to StackOverflow! Here, we expect questions to be supported by code, original research, examples, and other information about the specific problem you're facing. Please read and complete this checklist before asking questions. Try your hand at the solution and come back when you have a specific problem. Commented Aug 25, 2013 at 5:58
  • Possible duplicate of stackoverflow.com/questions/4725026/… Commented Aug 25, 2013 at 6:01
  • What is it supposed to do with the input "ABA"? Should it return "AB" or "ABA"? The term "duplicate letter(s)" seems to be ambiguous; several answers assume that it means adjacent duplicates only. Commented Aug 25, 2013 at 6:01

6 Answers 6

1

You can do that with regular expressions. e.g.:

private static final Pattern REGEX_PATTERN = 
        Pattern.compile("(.)\\1*");

public static void main(String[] args) {
    String input = "HELLO, AABBCC";

    System.out.println(
        REGEX_PATTERN.matcher(input).replaceAll("$1")
    );  // prints "HELO, ABC"
}
Sign up to request clarification or add additional context in comments.

1 Comment

This only removes adjacent duplicates. It will not remove duplicates from "ABABAB", for example.
1

I'm assuming that removing duplicates means that the result contains at most one occurrence of any character. (Some of the other answers assume that adjacent duplicates only need to be reduced to single occurrences.) The basic algorithm would be:

  • initialize the result to the empty string
  • loop through each character of the input and if the character is not already present in the result, append it to the result
  • return the result

A naive (and very inefficient) implementation would be:

private String removeAnyDuplicates(String userWord)
{
    String result = "";
    for (int i = 0; i < userWord.length(); ++i) {
        char c = result.charAt(i);
        if (result.indexOf(c) < 0) {
            // negative index indicates not present
            result += String.valueOf(c);
        }
    }
    return result;
}

This has two major sources of inefficiency: it creates many intermediate String objects and it has to scan the entire result so far for each character of the input. These problems can be solved by using some other built-in Java classes—a StringBuilder to more efficiently accumulate the result and a Set implementation to efficiently record and test which characters have already been seen:

private String removeAnyDuplicates(String userWord)
{
    int len = userWord.length();
    StringBuilder result = new StringBuilder(len);
    Set<Character> unique = new HashSet<Character>();
    for (int i = 0; i < len; ++i) {
        char c = result.charAt(i);
        // try to add c to set of unique characters
        if (unique.add(c)) {
            // if it succeeds, this is the first time seeing c
            result.append(c);
        }
    }
    return result.toString();
}

Comments

0
private String removeAnyDuplicates(String userWord)
{
    CharSequence inputStr = userWord;
    int length = inputStr.length();
    Set<Character> uniqueChars = new HashSet<Character>();

    for(int i=0; i < length; ++i) {
        uniqueChars.add(inputStr.charAt(i));
    }

    return uniqueChars.size() >= 3;
}

check out this answer

1 Comment

This is supposed to return String not boolean.
0

Convert the string to an array of char, and store it in a LinkedHashSet. That will preserve your ordering, and remove duplicates.

Like this:

private static String removeAnyDuplicates(String userWord)
    {
        char[] chars = userWord.toCharArray();
        Set<Character> charSet = new LinkedHashSet<Character>();
        for (char c : chars) {
            charSet.add(c);
        }

        StringBuilder sb = new StringBuilder();
        for (Character character : charSet) {
            sb.append(character);
        }

       return sb.toString();
    }

Remember:

import java.util.LinkedHashSet;
import java.util.Set;

Comments

0

You can try this

public static void main(String args[]){
    System.out.println(removeAnyDuplicates("HELLO"));
}

private static String removeAnyDuplicates(String userWord)
{
    char[] arr=userWord.toCharArray();
    List<String> list=new ArrayList<>();
    for(int i=0;i<arr.length;i++){
         if(!list.contains(String.valueOf(arr[i]))){
             list.add(String.valueOf(arr[i]));
         }
    }
    return list.toString().replaceAll("\\[|\\]|\\,","") ;
}

Comments

0

Try this one liner:

private String removeAnyDuplicates(String userWord) {
    return userWord.replaceAll("(.)\\1+", "$1");
}

This uses a regular expression to find repeated (2 or more) letters and replaces them with a single instance of the letter.


It is unclear if "repeated" means appearing immediately after or anywhere after. For anywhere, use this:

private String removeAnyDuplicates(String userWord) {
    return userWord.replaceAll("(.)(?=.*\\1)", "");
}

4 Comments

This only removes adjacent duplicates. It will not remove duplicates from "ABABAB", for example.
@ted isn't that what he wants?
@TedHopp see edits, which works but deletes the earlier repeats rather than the later, but still fulfils the contract
Very elegant. (I'm not sure it's the right answer for someone just learning Java, though. Probably reads like some sort of magical incantation.) If it's a school assignment, the rubric would probably be that "ABA" should return "AB", not "BA". But you're right that it fulfills the contract as stated.

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.