java hashmap solution


  • 0
    P

    public class Solution {
    public boolean wordPattern(String pattern, String str) {
    char[] c = pattern.toCharArray();
    String[] s = str.split(" ");
    if(s.length == 1)
    {
    if(c.length == 1)
    {
    return true;
    }
    return false;
    }
    if(c.length != s.length)
    {
    return false;
    }
    HashMap<Character,String> map = new HashMap<Character,String>();
    for(int i = 0;i<c.length;i++)
    {
    if(map.containsKey(c[i]))
    {
    if(!map.get(c[i]).equals(s[i]))
    {
    return false;
    }
    }
    else
    {
    if(map.containsValue(s[i]))
    {
    return false;
    }
    map.put(c[i],s[i]);
    }
    }
    return true;
    }
    }


Log in to reply
 

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