2. Algorithm question (given two lists of arrays, check whether the first string can be generated by characters in the second string)
Anonymous
public class CharacterCount { public static HashMap convertToMap(char[] charArr){ int count=1; HashMap hm = new HashMap(); for(char ch:charArr){ if(hm.containsKey(ch)){ count=hm.get(ch); count++; hm.put(ch,count); }else{ hm.put(ch,1); } } return hm; } public static boolean compare(char[] ch1,char[] ch2){ HashMap hm1 = convertToMap(ch1); HashMap hm2 = convertToMap(ch2); boolean result = false; for(Character key:hm1.keySet()){ if(hm1.get(key)==hm2.get(key)) result = true; else{ result = false; break; } } return result; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub char ch1[]={'a','b','a','b'}; char ch2[]={'b','a','b','a'}; System.out.println(compare(ch1,ch2)); } }
Check out your Company Bowl for anonymous work chats.