Word Pattern

来源:互联网 发布:淘宝店铺卖什么升级快 编辑:程序博客网 时间:2024/06/08 12:33

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Examples:

  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. pattern = "abba", str = "dog dog dog dog" should return false.
import java.util.HashMap;import java.util.Map;public class Solution {public static void main(String[] args) {// TODO Auto-generated method stub       System.out.println(Solution.wordPattern("abba","dog cat cat dog"));}    public static boolean wordPattern(String pattern, String str) {        String[] ss = str.split(" ");        if(pattern.length()!=ss.length)        return false;         Map<Character, String> map = new HashMap<>();        for(int i = 0 ; i < ss.length;i++)        {        char cc = pattern.charAt(i);        if(map.containsKey(pattern.charAt(i)))//当map包含该字符的时候        {  //判断对应取出的string是否等于ss中的string        if(!map.get(cc).equals(ss[i]))        {        return false;//不相等的话则返回false        }        }else        {        if(map.containsValue(ss[i]))//如果在对应的char没找到情况下 却在该位置上找到了ss,则返回false        return false;        map.put(cc, ss[i]);        }        }        return true;    }}


0 0