-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathExample5.java
56 lines (36 loc) · 1.27 KB
/
Example5.java
1
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
package applications.algorithms;
import java.util.HashMap;
import java.util.Scanner;
/**
* Finds the first non-repeated character in a
* user specified string.
*/
public class Example5 {
public static void findChar(String input) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
// populate the hash map
for (int i = 0; i < input.length(); ++i) {
char character = input.charAt(i);
if (!map.containsKey(character)) {
map.put(character, 1);
} else {
map.put(character, map.get(character) + 1);
}
}
// one more loop to find the first non-repeated character
for (int i = 0; i < input.length(); ++i) {
char character = input.charAt(i);
if (map.get(character) == 1) {
System.out.println("First non repeated character in " + input + " is: " + character);
break;
}
}
}
public static void main(String[] args){
// read the input string from user
Scanner scanner = new Scanner(System. in);
String inputString = scanner.nextLine();
System.out.println("You entered: " + inputString);
findChar(inputString);
}
}