I am having difficulty understanding the runtime and space complexity while implementing the said question.
Following is the code:
import java.util.HashMap;
import java.util.Map;
public class AnagaramInBigString {
private static Map<Character, Integer> frequencyMap(String str)
{
Map<Character, Integer> source = new HashMap<Character,Integer>();
for(int i = 0; i < str.length(); i++)
{
if(str.charAt(i) == ' ')
{
continue;
}
else
{
if(source.containsKey(str.charAt(i)))
{
source.put(str.charAt(i), source.get(str.charAt(i) + 1));
}
else source.put(str.charAt(i), 1);
}
}
return source;
}
public static void main(String []args)
{
String check= "BACDGABCDA";
String sample = "ABCD";
System.out.println(sample.length());
for(int i= 0; i <= check.length() - sample.length() ; i++)
{
String checkSub = check.substring(i, i + sample.length());
System.out.println(checkSub);
System.out.println(frequencyMap(checkSub).equals(frequencyMap(sample)));
}
}
}
Is the time complexity O(check*sample)
? Space complexity is O(sample)
?
Also please suggest on how I can improve the efficiency of this code.
Like:
- I can calculate the hashmap for sample string only once instead of doing it again and again with every iteration.