8 lines Java solution without extra space, no hashtable!

  • 0
    public boolean wordPattern(String pattern, String str) {
        if(pattern.length()!=str.split(" ").length) return false;
        for(int i=0; i<pattern.length(); i++){
            for(int j=i+1; j<pattern.length(); j++){
                    if(!str.split(" ")[j].equals(str.split(" ")[i])) return false;
                }else if(str.split(" ")[j].equals(str.split(" ")[i])) return false;
        return true;

Log in to reply

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