Home > Java > javaTutorial > How to find the first non-repeating character in Java?

How to find the first non-repeating character in Java?

王林
Release: 2023-04-21 21:04:06
forward
1215 people have browsed it

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;     } }
Copy after login

The output results are as follows:

王 默 null
Copy after login

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!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
Install JAVA
From 1970-01-01 08:00:00
0
0
0
Unable to install java
From 1970-01-01 08:00:00
0
0
0
Can java be used as the backend of the web?
From 1970-01-01 08:00:00
0
0
0
Is this in Java language?
From 1970-01-01 08:00:00
0
0
0
Help: JAVA encrypted data PHP decryption
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template