Given some strings, ab,abc,ad, ace, ddd ... from a file, to find out whether some string S is in the strings. If I want to use a hash to check the existence of the S.
Algorithm analysis: Since each 'put' operation takes O(1) * K time, where K is the length of the string, the building up of the map takes O(n * K) time, where n is the number of string. And the look up takes constant time, so the overall time is O(n*k). Is this the right thought? While we often say hash table allows constant time look up, it typically ignores the time spent on building up the hash. When answering a question like this, should I say the time complexity is O(n*k), or just O(n)? Thanks a lot. Just started to learn algorithm analysis.
String line = null;
BufferedReader br = new BufferedReader(new File("file.txt"));
HashMap<String, Integer> strs = new HashMap<String,Integer>();
while((line=br.readLine()) != null){
Integer count = strs.get(line);
if( count == null){
strs.put(line, 1);
}
count++;
}
// Suppose the string to be checked is "str";
if(strs.contains(str)){
return true;
}
return false;