Flipkart Interview Question
Software Engineer / Developers1. split given string by space dilimiter
2. Put each string in hashtable like key=string, value=count
3. Now check each given array of tokens against hashtable and get the counts
Let me know if you need code..
import java.util.HashMap;
import java.util.Map;
public class StringTokens {
private static String [] tokens = {"This", "is", "boy"} ;
private static String text = "this is the new tech this boy and where is this boy and there is this boy";
public static void main(String [] args) {
printTokenCount();
}
public static void printTokenCount() {
//tokenize the text
String [] tokenized = text.split(" ");
Map<String,Integer> tokenMap = new HashMap<String,Integer>();
for (String s: tokenized) {
if (!tokenMap.containsKey(s)) {
tokenMap.put(s, new Integer(1));
} else {
int count = tokenMap.get(s);
tokenMap.put(s, ++count);
}
}
for (String s: tokens) {
s=s.toLowerCase();
if (tokenMap.containsKey(s)) {
int count = tokenMap.get(s);
System.out.println(s + " : " + count);
}
}
}
}
import java.util.*;
public class test {
private static String [] tokens = {"This", "is", "boy"} ;
private static String text = "this is the new tech this boy and where is this boy and there is this boy";
public static void main(String[] args) {
for(String s : tokens)
{
System.out.print("\ntoken "+s);
String[] tokens1 = text.split(s);
System.out.print("\tcount " + tokens1.length);
}
}
}
import java.util.*;
import java.util.HashSet;
public class CountOccurs{
public static void main(String[] args) {
String strarr[] = { "pras", "ram","vino","pras","pras"};
String str="pras";
CountOccurs oc= new CountOccurs();
System.out.println("The string occurs"+oc.count(str,strarr));
}
public int count(String str, String []strarr){
int i=0;
List text=Arrays.asList(strarr);
int count=0;
for(i=0;i<text.size();i++){
if(text.get(i).equals((str))){
count++;
}
}
return count;
}
}
This is my understanding...
String.split() will not work for the case "fofofofof" and token is "fo".. in this case the array will have only one element empty_string.
<pre lang="" line="1" title="CodeMonkey54200" class="run-this">public class Test{
public void go(){
String s = "fofofofof";
String[] s1 = s.split("fo");
for(String a : s1)
System.out.println("Token = #"+a+"#");
System.out.println("Total Number of Tokens = "+s1.length);
}
public static void main(String... args){
Test t = new Test();
t.go();
}
}
/*
Output
======
Token = ##
Token = ##
Token = ##
Token = ##
Token = #f#
Total Number of Tokens = 5
*/</pre><pre title="CodeMonkey54200" input="yes">
</pre>
cant we use KMP to process each of string tokens ...the complexity will be O(m*n) where n is length of string and m is count of total no of tokens
- ankur September 22, 2011