My Java Hashtable Solution


  • 7
    M
    import java.util.Hashtable;
    public class Solution {
        public boolean wordPattern(String pattern, String str) {
            String[] arr = str.split(" ");
            int len = pattern.length();
            if(arr.length != len){
                return false;
            }
            Hashtable<Character, String> table = new Hashtable<Character, String>();
            for( int i = 0; i < len; i++){
                char c = pattern.charAt(i);
                if( table.containsKey(c) && !table.get(c).equals(arr[i])){
                    return false;
                }
                else if( !table.containsKey(c) && table.contains(arr[i])){
                    return false;
                }
                else{
                    table.put(c, arr[i]);
                }
            }
            return true;
        }
    }

  • 0
    E

    HashMap might be a better alternative because it is faster than HashTable. Good answer anyway!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.