Simple JAVA solution beats 99% without HashTable


  • -2
    W
    public class Solution {
    public boolean wordPattern(String pattern, String str) {
        int p1, p2;
        boolean flag = true;
        p1 = 0;
        p2 = pattern.length()-1;
        String[] strSet = str.split(" ");
        
        if(pattern.length() != strSet.length) return false;
        
        for(int i=0; i<pattern.length(); i++){
            if(pattern.charAt(p1) == pattern.charAt(p2)){
                if(strSet[p1].equals(strSet[p2])) flag = true;
                else return false;
            }else{
                if(!strSet[p1].equals(strSet[p2])) flag = true;
                else return false;
            }
            if(i%2 == 0) p1++;
            else p2--;
        }
        return flag;
    }
    

    }


  • 0
    M

    Thanks for sharing, but I think it's not correct.
    e.g.
    pattern: abaaba
    str: x y z z y x
    It should be false but the program returns true.
    The test cases are not comprehensive I think.


Log in to reply
 

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