Java Concept Of The Day
How To Find First Repeated And Non-Repeated Character In A String?
Given a string, your code must find out the first repeated as well as non-repeated character in that string. For example, if “JavaConceptOfTheDay” is the given string, then ‘J’ is a first non-repeated character and ‘a’ is a first repeated character. Have a look at the below image.
How To Find First Repeated And Non-Repeated Character In A String?
Step 1 : Define one HashMap called charCountMap with Character as key and Integer as value. This map will hold the characters and their count in the given string.
Step 2 : Convert inputString to char array called strArray.
Step 3 : Iterate through all chars of strArray and update their occurrences in charCountMap.
Step 4 : Iterate through all chars of strArray and check their count in charCountMap. Any first occurring character with 1 as it’s count will be the first non-repeated character in inputString.
Step 5 : Iterate through all chars of strArray and check their count in charCountMap. Any first occurring character with >1 as it’s count will be the first repeated character in inputString.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
| import java.util.HashMap; import java.util.Scanner; public class MainClass { static void firstRepeatedNonRepeatedChar(String inputString) { HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>(); char [] strArray = inputString.toCharArray(); for ( char c : strArray) { if (charCountMap.containsKey(c)) { //If char is present in charCountMap, incrementing it's count by 1 charCountMap.put(c, charCountMap.get(c)+ 1 ); } else { charCountMap.put(c, 1 ); } } for ( char c : strArray) { if (charCountMap.get(c) == 1 ) { System.out.println( "First Non-Repeated Character In '" +inputString+ "' is '" +c+ "'" ); break ; } } for ( char c : strArray) { if (charCountMap.get(c) > 1 ) { System.out.println( "First Repeated Character In '" +inputString+ "' is '" +c+ "'" ); break ; } } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println( "Enter the string :" ); String input = sc.next(); firstRepeatedNonRepeatedChar(input); } } |
Output :
Enter the string :
JavaConceptOfTheDay
First Non-Repeated Character In ‘JavaConceptOfTheDay’ is ‘J’
First Repeated Character In ‘JavaConceptOfTheDay’ is ‘a’
Comments
Post a Comment