290. Word Pattern

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.

Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

题目含义:给定一个模式,判断句子中的单词是否满足模式?

 

复制代码
 1     public boolean wordPattern(String pattern, String str) {
 2         if(str.split(" ").length != pattern.length()) return false;
 3         Map<Character,String> map = new HashMap<>(pattern.length());//维护pattern字符与后面字符串的映射关系
 4         Map<String,Boolean> valueMap = new HashMap<>();
 5         
 6         char p_arra[] = pattern.toCharArray();
 7         String str_arra[] = str.split(" ");
 8         int index=0;
 9         while (index<p_arra.length)
10         {
11             if (!map.containsKey(p_arra[index]))
12             {
13                 if (valueMap.containsKey(str_arra[index])) return false;
14                 map.put(p_arra[index],str_arra[index]);
15                 valueMap.put(str_arra[index],true);
16             }else if (!map.get(p_arra[index]).equals(str_arra[index])) return false;
17             index++;
18         }
19         return true;        
20     }
复制代码

 

posted @   daniel456  阅读(175)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示