Home > Enterprise >  how to delete characters that appear more than once in a string in JAVA, and keep only the first cha
how to delete characters that appear more than once in a string in JAVA, and keep only the first cha

Time:04-30

how to delete characters that appear more than once in a string in JAVA, 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:

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