Interview Question
SDE-2sCountry: United States
Interview Type: In-Person
Read the string and count the ' ' characters:
public static int countSpaceDelimSubstrings(String str){
return countDelimSubstrings(str, ' ');
}
public static int countDelimSubstrings(String str, char delim){
if(str == null){
throw new NullPointerException("\"str\" may not be null");
}
int count = 0;
boolean lastWasDelim = true;
for(char c : str.toCharArray()){
if(c != delim){
if(lastWasDelim){
count++;
lastWasDelim = false;
}
}
else{
lastWasDelim = true;
}
}
return count;
}
edits:
Changes some semantic errors that do not affect the logic
How will you handle the big size string chunks? Remember that the input data is very bulky....
@Vikas:
Barring a few unrelated semantic errors, the code operates correctly. I've run the code with the input 'a bbbbb c ddddd' and it correctly returned 4.
As to those semantic changes:
I changed line 2 from:
return countDelimChars(str, ' ');
to
return countDelimSubstrings(str, ' ');
and
for(char c : str.getChars()){
to
for(char c : str.toCharArray()){
Couldn't you just do it like this?
public static int countWords(String s) {
String[] words = s.split(" ");
return words.length;
}
Or am I misunderstanding something?
yes you are right except for the major 5 GB data, the idea is to use the stream reader like BufferedReader or something like that, you don't load everything into the main memory and load line or line or chunks of data and apply this logic. The assumption each line is self contained i.e. it does not have any dependencies on other lines..
Precisely when a lazy language is awesome
countWords :: [Char] -> Int
countWords = foldl f 0
where
f :: Int -> Char -> Int
f v ' ' = v + 1
f v _ = v
public static int count(String str){
//covert str to a char Array
char [] array = str.toCharArray();
// Iterate through char array from array[0] to a[length-1] packing up
// words in an arrayList as you go
int beginIndex =0;
//check if the first character is a delimiter or a "normal" character
if (array[beginIndex] == ' '){
//search for first 'normal' character
while(array[beginIndex] == ' ') beginIndex++;
}//
ArrayList<String> words = new ArrayList<String>();
String word = null;
int i = beginIndex +1;
while(i <array.length){
if( array[i] == ' '){
word = str.substring(beginIndex, i);
words.add(word);
while(array[i] == ' ')
i++;
beginIndex = i;
}//if
i++;
}//while
word = str.substring(beginIndex, str.length());
words.add(word);
//return size of arraylist
return words.size();
}//count(String)
public class WordCount{
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "Hi Hello How are you kdfngndfgkjnffjkdjng sa d d d";
int len= s.length();
int count =0;
int index = 0;
for(int i=0;i<len;++i){
char c = s.charAt(index);
if(s.charAt(i)==' '){
index = index+1;
}
}
System.out.println(index+1);
}
}
- Dj January 19, 2015