Java Exercises: Find the index of first non-repeating character in a given string
Java Basic: Exercise-187 with Solution
Write a Java program to find the index of first non-repeating character in a given string.
Pictorial Presentation:
Sample Solution:
Java Code:
import java.util.*;
public class Solution {
public static void main(String[] args) {
String str1 = "google";
System.out.println("Index of first non-repeating character in '" + str1 + "' is: " + first_unique_character(str1));
}
public static int first_unique_character(String str1) {
HashMap < Character, Integer > map = new HashMap < > ();
for (int i = 0; i < str1.length(); ++i) {
char chr = str1.charAt(i);
map.put(chr, map.containsKey(chr) ? map.get(chr) + 1 : 1);
}
for (int i = 0; i < str1.length(); ++i) {
if (map.get(str1.charAt(i)) < 2) {
return i;
}
}
return -1;
}
}
Sample Output:
Index of first non-repeating character in 'google' is: 4
Flowchart:
Java Code Editor:
Company: Microsoft Amazon Bloomberg
Contribute your code and comments through Disqus.
Previous: Write a Java program to check if a number is a strobogrammatic number. The number is represented as a string.
Next: Write a Java program to find all the start indices of a given string 's anagrams in another given string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework