1ms 99.5% Java Solution


  • 2
    O
       public class Solution {
            public boolean partition(String str, ArrayList<String> b) {
                if (str.length()==0) return false;
                int prev=-1, i=str.indexOf(' ');
                while (i!=-1) {
                    b.add(str.substring(prev+1,i));
                    prev=i;
                    i=str.indexOf(' ',i+1);
                }
                b.add(str.substring(prev+1));
                return true;
            }
            
            public boolean wordPattern(String pattern, String str) {
                ArrayList<String> b = new ArrayList<String>();;
                if (!partition(str,b)) return false;
                if (b.size()!=pattern.length()) return false;
                String[] map = new String[26];
                HashSet<String> mapped = new HashSet<String>();
                for (int i=0; i<pattern.length(); i++)
                    if (map[pattern.charAt(i)-'a']==null) {
                        if (mapped.contains(b.get(i))) return false;
                        mapped.add(b.get(i));
                        map[pattern.charAt(i)-'a']=b.get(i);
                    } else {
                        if (!map[pattern.charAt(i)-'a'].equals(b.get(i))) return false;
                    }
                return true;
                        
            }
        }

  • 1
    C

    Well done. HashSet is tatolly enough here than HashMap;


Log in to reply
 

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