Implement a function that takes a string and returns the first character that does not appear twice or more.
Example:
- "abacc" -> 'b' ('a' appears twice, and so does 'c')
- "xxyzx" -> 'y' ('y' and 'z' are non-repeating characters, and 'y' appears first)
If there is no non-repeating character, return null.
풀이
import java.util.*;
public class NR {
public static void main(String[] args) {
// NOTE: The following input values will be used for testing your solution.
nonRepeating("abcab"); // should return 'c'
nonRepeating("abab"); // should return null
nonRepeating("aabbbc"); // should return 'c'
nonRepeating("aabbdbc"); // should return 'd'
}
// Implement your solution below.
public static Character nonRepeating(String s) {
LinkedList<Character> characters = new LinkedList<>();
List<Character> characterList = new ArrayList<>();
Character c = null;
for (int i = 0; i < s.length(); i++) {
if (!characters.contains(s.charAt(i))) {
characters.add(s.charAt(i));
} else {
if (!characterList.contains(s.charAt(i))) {
characterList.add(s.charAt(i));
}
}
}
for (int i = 0; i <characterList.size(); i++){
int index = characters.indexOf(characterList.get(i));
characters.remove(index);
}
if (characters.size() > 0) {
c = characters.getFirst();
}
return c;
}
}
'Algorithms > 11 Coding Interview (CS Dojo)' 카테고리의 다른 글
Assign Numbers in Minesweeper (Java) (0) | 2018.03.14 |
---|---|
One Away Strings (Java) (0) | 2018.03.13 |
Is One Array a Rotation of Another? (Java) (0) | 2018.02.13 |
Common Elements in Two Sorted Arrays (Java) (0) | 2018.02.13 |
Common Elements in Two Sorted Arrays (Java) (0) | 2018.02.08 |