Home >Java >javaTutorial >How to find the first non-repeating character in Java?
How to find the first non-repeating character from a string?
For example, in the string "Silent King Shen Silent Two", the first non-repeating character is "King", right? Because "Shen" is repeated, "Mo" is repeated.
public class FindNonRepeatingChar { public static void main(String[] args) { System.out.println(printFirstNonRepeatingChar("沉默王沉沉默二")); System.out.println(printFirstNonRepeatingChar("沉默王沉")); System.out.println(printFirstNonRepeatingChar("沉沉沉")); } private static Character printFirstNonRepeatingChar(String string) { char[] chars = string.toCharArray(); List<Character> discardedChars = new ArrayList<>(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (discardedChars.contains(c)) continue; for (int j = i + 1; j < chars.length; j++) { if (c == chars[j]) { discardedChars.add(c); break; } else if (j == chars.length - 1) { return c; } } } return null; } }
The output results are as follows:
王 默 null
Let me talk about my ideas:
1) Split the string into a character array.
2) Declare a List and put repeated characters into it.
3) The outer for loop starts from the first character. If it is already in the List, continue to the next round.
4) The nested for loop starts traversing from the next character (j = i 1) of the first character. If it finds a duplicate of the previous character, it is added to the List and jumps out of the inner layer. Loop; if the last (j == chars.length - 1) is not found, it is the first non-repeating character, right?
The above is the detailed content of How to find the first non-repeating character in Java?. For more information, please follow other related articles on the PHP Chinese website!