public class Solution { /** * @param s: The first string * @param b: The second string * @return true or false */ public boolean anagram(String s, String t) { // write your code here Map<String , Integer> sMap = new HashMap<String , Integer>(); Map<String , Integer> tMap = new HashMap<String , Integer>(); if(s.length() != t.length()){ return false; } int i=0; int wCount=0; while(i<s.length()){ if(sMap.containsKey(s.substring(i,i+1))){ wCount=sMap.get(s.substring(i,i+1)).intValue(); wCount++; sMap.put(s.substring(i,i+1) , new Integer(wCount)); } else{ sMap.put(s.substring(i,i+1) , new Integer(1)); } i++; } i=0; while(i<t.length()){ if(tMap.containsKey(t.substring(i,i+1))){ wCount=tMap.get(t.substring(i,i+1)).intValue(); wCount++; tMap.put(t.substring(i,i+1) , new Integer(wCount)); } else{ tMap.put(t.substring(i,i+1) , new Integer(1)); } i++; } Set sEntrySet = sMap.entrySet(); Iterator sIterator = sEntrySet.iterator(); while(sIterator.hasNext()){ Map.Entry pair = (Map.Entry)sIterator.next(); if(! tMap.containsKey(pair.getKey()) ){ return false; }else{ if(((Integer)tMap.get(pair.getKey())).intValue() != ((Integer)(pair.getValue())).intValue()){ return false; } } } return true; } }
时间: 2024-10-12 17:14:18