Skip to content

Commit 5301dac

Browse files
Create Interview5
1 parent 145308e commit 5301dac

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

src/main/java/pramp/Interview5

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* Split the words in a given string and print all of them in the descending order of their occurences count.
3+
*
4+
* @author: shivam.maharshi
5+
*/
6+
class Pramp {
7+
8+
// 1. Parse the doc and figure out words split by space, punctuations or both.
9+
// 2. Store them in a HasHMap and keep occurences count.
10+
// 3. Traverse HashMap keyset and sort it.
11+
// 4. Time: O(nLog(n)): where n are the words. Space: O(n)
12+
13+
public static void getCount(String s) {
14+
if (s==null || s.length() == 0)
15+
return;
16+
// This returns only words as array from s.
17+
// String[] words = s.split("\\W+");
18+
Map<String, Integer> m = new HashMap<>();
19+
s = s.toLowerCase();
20+
StringBuilder sb = new StringBuilder();
21+
int i = 0;
22+
while (i < s.length()) {
23+
char c = s.charAt(i);
24+
if (isWordChar(c))
25+
sb.append(c);
26+
else if (!sb.isEmpty())
27+
addWord(m, sb);
28+
i++;
29+
}
30+
if (!sb.isEmpty())
31+
addWord(m, sb);
32+
System.out.println(m.toString());
33+
}
34+
35+
public static boolean isWordChar(char c) {
36+
return (c =< '9' && c >= '0') || (c =< 'z' && c >= 'a');
37+
}
38+
39+
public static void addWord(Map<String, Integer> m, StringBuilder sb) {
40+
String word = sb.toString();
41+
if (m.contains(word))
42+
m.put (word, m.get(word) + 1);
43+
else
44+
m.put (word, 1);
45+
sb = new StringBuilder();
46+
}
47+
48+
}

0 commit comments

Comments
 (0)