First Not Repeating Character in String - The Coding Shala
Home >> Interview Questions >> First Not Repeating Character
Other Posts You May Like
In this post, we will learn how to find the First Not Repeating Character in a String and will write a Java program for the same.
First Not Repeating Character in a String
Given a string s consisting of small English letters, find and return the first instance of a non-repeating character in it. If there is no such character, return '_'.
Example 1:
For s = "abacabad", the output should be firstNotRepeatingCharacter(s) = 'c'.
There are 2 non-repeating characters in the string: 'c' and 'd'. Return c since it appears in the string first.
Example 2:
For s = "abacabaabacaba", the output should be firstNotRepeatingCharacter(s) = '_'.
There are no characters in this string that do not repeat.
First Not Repeating Character in a String Java Program
Approach 1
We will use HashMap to count the occurrence of each character then will return if the count of a char is 1.
Java Program:
char firstNotRepeatingCharacter(String s) { char[] arr = s.toCharArray(); HashMap<Character, Integer> map = new HashMap<>(); for(int i=0;i<arr.length;i++){ if(map.containsKey(arr[i])){ map.put(arr[i], map.get(arr[i])+1); } else{ map.put(arr[i], 1); } } for(int i=0;i<arr.length;i++){ if(map.get(arr[i])==1) return arr[i]; } return '_'; }
Approach 2
We can use String methods indexOf() and lastIndexOf(). If both the methods return the same index that means char occur only once in the string.
Java Program:
char firstNotRepeatingCharacter(String s) { char[] arr = s.toCharArray(); for(int i=0;i<arr.length;i++){ if(s.indexOf(arr[i])==s.lastIndexOf(arr[i])) return arr[i]; } return '_'; }
Other Posts You May Like
- First Unique Character in a String
- How to Evaluate Reverse Polish Notation
- Longest Common Prefix
- Valid Parentheses
- Add Binary
Comments
Post a Comment