
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find First Non-Repeating Character from a Stream of Characters in Java
Finding the first non-repeating character in a string is a common programming problem. It involves finding the first character that appears only once in the string. This task helps understand how to manipulate strings and use basic data structures in Java.
Problem Statement
Given a string, identify the first character that does not repeat. If all characters repeat, indicate that there is no non-repeating character.
Input
tutorialspoint
Output
The first non-repeating character of the string is T
Steps to find the first non-repeating character from a stream of characters
Below are the steps to find the first non-repeating character from a stream of characters ?
- Initialize by using an ArrayList to track characters that might be non-repeating.
- Use a boolean array to mark characters that appear more than once.
- Loop through each character in the string, if the character is not repeating and not in the list, add it to the list, and if in the list, remove it from the list and mark it as repeating.
- The first character in the list is the first non-repeating character.
- If the list is empty, no non-repeating character is found.
Example
To find the first non-repeating character from a stream of characters, the Java code is as follows ?
import java.util.ArrayList; import java.util.List; public class Demo { final static int max_chars = 256; static void non_repeating_char() { List<Character> my_list = new ArrayList<Character>(); boolean[] repeat = new boolean[max_chars]; String my_str = "tutorialspoint"; for (int i = 0; i < my_str.length(); i++) { char x = my_str.charAt(i); if (!repeat[x]) { if (!my_list.contains(x)) { my_list.add(x); } else { my_list.remove((Character) x); repeat[x] = true; } } } if (my_list.size() != 0) { System.out.println("The first non-repeating character is " + my_list.get(0)); } else { System.out.println("No non-repeating character found"); } } public static void main(String[] args) { non_repeating_char(); } }
Output
The first non-repeating character of the string is u
Code Explanation
A class named Demo contains a function named the non_repeating_char function. A list is created and a string is defined. This string is iterated over, every character is inspected, and its count is stored as a Boolean variable, in an array named repeat. The value will be true if it is repeated and false otherwise. The main function is called, and the relevant message is displayed on the console.