Skip to content

Commit 8b69a49

Browse files
committed
Non-repeating character
1 parent 7038c81 commit 8b69a49

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

src/easy/NonrepeatingCharacter.java

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package easy;
2+
3+
import java.util.HashMap;
4+
5+
/**
6+
* Have the function NonrepeatingCharacter(str)
7+
* take the str parameter being passed,
8+
* which will contain only alphabetic characters and spaces,
9+
* and return the first non-repeating character.
10+
* ---
11+
* For example: if str is "agettkgaeee" then your program should return k.
12+
* The string will always contain at least one character and there will
13+
* always be at least one non-repeating character.
14+
*/
15+
public class NonrepeatingCharacter {
16+
17+
/**
18+
* Non-repeating Character function.
19+
*
20+
* @param str input string
21+
* @return the first non-repeating character
22+
*/
23+
private static String nonrepeatingCharacter(String str) {
24+
25+
char[] charArr = str.toLowerCase().toCharArray();
26+
HashMap<Integer, Integer> freq = new HashMap<>();
27+
28+
for (int c : charArr) {
29+
Integer count = freq.get(c);
30+
freq.put(c, count == null ? 1 : ++count);
31+
}
32+
33+
for (int c : charArr) {
34+
Integer count = freq.get(c);
35+
if (count == 1) {
36+
return String.valueOf((char) c);
37+
}
38+
}
39+
return "false";
40+
}
41+
42+
/**
43+
* Entry point.
44+
*
45+
* @param args command line arguments
46+
*/
47+
public static void main(String[] args) {
48+
var res1 = nonrepeatingCharacter("Beauty in things exists in the mind which contemplates them");
49+
System.out.println(res1);
50+
var res2 = nonrepeatingCharacter("A wise man apportions his beliefs to the evidence");
51+
System.out.println(res2);
52+
}
53+
54+
}

0 commit comments

Comments
 (0)