Skip to content

Commit 639b4b6

Browse files
print first non repeated character from String
One of the most common string interview questions: Find the first non-repeated (unique) character in a given string. for Example if given String is "Morning" then it should print "M". This question demonstrates efficient use of Hashtable. We scan the string from left to right counting the number occurrences of each character in a Hashtable. Then we perform a second pass and check the counts of every character. Whenever we hit a count of 1 we return that character, that’s the first unique letter. Be prepared for follow-up question for improving memory efficiency, solving it without hash table as well.
1 parent a060183 commit 639b4b6

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

Challenge03.java

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package challenge03;
2+
3+
import static org.junit.Assert.assertTrue;
4+
5+
import java.util.LinkedHashMap;
6+
import java.util.Map;
7+
8+
import org.junit.jupiter.api.Test;
9+
10+
/**
11+
* The Class Challenge03.
12+
*
13+
* Given a string, your code must find out the first repeated as well as
14+
* non-repeated character in that string. For example, if “JavaConceptOfTheJay”
15+
* is the given string, then ‘v’ is a first non-repeated character and ‘a’ is a
16+
* first repeated character.
17+
*/
18+
public class Challenge03 {
19+
20+
public Character[] findNonRepatedAndRepeatedChar(String input) {
21+
Character[] toReturn = new Character[2];
22+
if (input == null || input.isEmpty()) {
23+
return toReturn;
24+
} else {
25+
Map<Character, Integer> map = new LinkedHashMap<Character, Integer>();
26+
for (int i = 0; i < input.length(); i++) {
27+
Integer oldValue = map.put(input.charAt(i), 0);
28+
if (null != oldValue) {
29+
map.put(input.charAt(i), oldValue + 1);
30+
}
31+
}
32+
boolean nonRepeatedFound = false;
33+
boolean repeatedFound = false;
34+
for (Character c : map.keySet()) {
35+
if (map.get(c) == 0 && !nonRepeatedFound) {
36+
toReturn[0] = c;
37+
nonRepeatedFound = true;
38+
}
39+
if (map.get(c) > 0 && !repeatedFound) {
40+
toReturn[1] = c;
41+
repeatedFound = true;
42+
}
43+
}
44+
}
45+
46+
return toReturn;
47+
48+
}
49+
50+
@Test
51+
public void test() {
52+
Challenge03 tester = new Challenge03();
53+
Character[] cs= tester.findNonRepatedAndRepeatedChar("avaConceptOftheDay");
54+
System.out.println(cs[0] +" , " +cs[1]);
55+
assertTrue(cs[0].equals('v'));
56+
assertTrue(cs[1].equals('a'));
57+
58+
59+
}
60+
}

0 commit comments

Comments
 (0)