java - Email content needs to be filtered out with words in a dictionary -


i asked question in interview. question input string (which might come email or large text file) needs filtered list of bad words , replaced else.

for example, if input string contains bad words exist in list of bad words, bad word needs replaced else, empty string or wild card character.

the solution came put bad words in hashmap , put input string in stringbuffer , retrieve word word delimited space , check if word exists in hashmap, if exists, replace word empty string. interviewer said manipulating stringbuffer might expensive, because stringbuffer maintains array of characters. replacing means needs copy new array.

does have better algorithm instead of solution?

thanks.

you can first parse string string[] (using split()) and, iterate on words , check if word needed replaced looking in hashmap<string,string> of blacklisted words. (if is, replace reference 'replace to' [the value of string in map], , not create new string). then, using stringbuilder, rebuild new string.

should that:

public static string replacestring(map<string,string> map,string input) {      string[] arr = input.split("\\s");     (int = 0;i<arr.length;i++) {          string val = map.get(arr[i]);         if (val != null) arr[i] = val;     }     stringbuilder sb = new stringbuilder();     (string s : arr) {         if (s == null || s.length() == 0 ) continue;         sb.append(s).append(' ');     }     return sb.tostring().trim(); } 

Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -