I was asked a question in an interview. The question was that the input string (which might come from email or large text file) needs to be filtered with list of bad words and replaced with something else.
for example, if the input string contains bad words which exist in a list of bad words, the bad word needs to be replaced with something else, something like empty string or wild card character.
The solution that I came up with was to put all the bad words in a hashmap and put input string in a StringBuffer and retrieve word by word delimited by space and check if word exists in hashmap, if it exists, replace the word with empty string. But the interviewer said that manipulating StringBuffer might be expensive, because stringBuffer maintains an array of characters. Replacing means it needs to copy to a new array.
Does anybody have a better algorithm instead of this solution?
Thanks.
you can first parse the
StringintoString[](usingsplit()) and, iterate over the words and check if a word is needed to be replaced by looking for it in yourHashMap<String,String>of blacklisted words. (if it is, you just replace the reference with the ‘replace to’ [the value of the String in the map], and do not create a new string). then, usingStringBuilder, rebuild your new string.should look something like that: