Home > Software engineering >  How to delete characters that appear more than once in a string, and keep only the first character a
How to delete characters that appear more than once in a string, and keep only the first character a

Time:05-01

How to delete characters that appear more than once in a string, and keep only the first character and return the result?

Example:

input: String bananas
output: String bans

CodePudding user response:

  1. Use a local variable to hold an empty String

  2. Loop thru the input string

  3. Keep appending the current character to local variable as long as local variable doesn't contain the character at the current position

     String s1 = "";
     for (int i=0; i < s.length(); i  ){
         if (!s1.contains(""   s.charAt(i))){
             s1  = s.charAt(i);
         }
     }
    

CodePudding user response:

Code points

When working with individual characters one-by-one, use code point integers. You will often see char primitives or Character objects being used, but that type has been essentially broken since Java 2, and legacy since Java 5.

You can get the code points of a string's characters as an IntStream by calling String#codePoints. From there we eliminate duplicates by calling IntStream#distinct. The remaining code point int values can be collected by appending to a StringBuilder object. Lastly, we convert the mutable StringBuilder to an immutable String object.

String distinct =
        "bananas"
                .codePoints()
                .distinct()
                .collect( StringBuilder :: new , StringBuilder :: appendCodePoint , StringBuilder :: append )
                .toString();

See this code run live at IdeOne.com.

bans

CodePudding user response:

Sounds like an interview question.
Try the following steps:

  1. create int[26]- holds visit count for each letter assuming inputs are always lowercase
  2. loop thru the input
    • append to the output when the letter is not visited
    • update the visit count
  • Related