My Java 2ms solution - direct but not simple


  • 0
    H
    public class Solution {
        public boolean wordPattern(String pattern, String str) {
            String[] s = str.split(" ");
            int n = pattern.length();
            if(n != s.length){
                return false;
            } else{
                int a[] = new int[n];
                int b[] = new int[n];
                for(int i = 1; i<n; i++){
                    for(int j = 0; j<i; j++){
                        if(pattern.charAt(j) == pattern.charAt(i)){
                            a[i] = a[j];
                            break;
                        }
                        a[i] =i;
                    }
                }
                for(int i = 1; i<n; i++){
                    for(int j = 0; j<i; j++){
                        if(s[j].equals(s[i])){
                            b[i] = b[j];
                            break;
                        }
                        b[i] =i;
                    }
                }
                for(int j = 0; j<n; j++){
                    if(a[j] != b[j]){
                        return false;
                    }
                }
                return true;
            }
        }
    }

Log in to reply
 

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