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:
Use a local variable to hold an empty String
Loop thru the input string
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:
- create int[26]- holds visit count for each letter assuming inputs are always lowercase
- loop thru the input
- append to the output when the letter is not visited
- update the visit count