leetcode 290:Word Pattern
来源:互联网 发布:raysource 软件下载 编辑:程序博客网 时间:2024/06/02 07:16
题目描述:
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:
pattern = “abba”, str = “dog cat cat dog” should return true.
pattern = “abba”, str = “dog cat cat fish” should return false.
pattern = “aaaa”, str = “dog cat cat dog” should return false.
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.
解题思路:
第一种方案:
使用一个hashMap《Character,String》 key保存pattern中的字符,value保存words中的字符串,
比较相同key值的value是否相同
public boolean wordPattern(String pattern , String str){ HashMap<Character,String> map = new HashMap<Character,String>(); String[] words = str.split(" "); if(words.length!=pattern.length()) return false; for(int i =0 ; i<words.length;i++){ if(!map.containsKey(pattern.charAt(i))){ if(map.containsValue(words[i])) return false; map.put(pattern.charAt(i), words[i]); }else if(!map.get(pattern.charAt(i)).equals(words[i])){ return false; } } return true; }
第二种方案:
利用hashMap put方法返回值的特性,比较pattern 和word对应的下标是否一致
public boolean wordPattern(String pattern, String str) { String[] words = str.split(" "); if (words.length != pattern.length()) return false; Map map = new HashMap(); for (Integer i=0; i<words.length; ++i) if (map.put(pattern.charAt(i), i) != map.put(words[i], i)) return false; return true; }
- leetcode 290: Word Pattern
- [leetcode 290]Word Pattern
- LeetCode 290 Word Pattern
- [LeetCode 290] Word Pattern
- leetcode 290 Word Pattern
- [leetcode 290] Word Pattern
- LeetCode 290 Word Pattern
- 【LEETCODE】290-Word Pattern
- LeetCode 290:Word Pattern
- leetcode 290 Word Pattern
- leetcode 290: Word Pattern
- 【LeetCode-290】Word Pattern
- LeetCode 290 Word Pattern
- leetcode 290:Word Pattern
- LeetCode[290] Word Pattern
- Leetcode 290 Word Pattern
- [leetcode][290]Word Pattern
- leetcode-290-Word Pattern
- asp.net控件库FineUI使用入门图解
- iOS学习笔记33-UICollectionView入门
- 【原创】一种实现IBM MQ通道传输能力垂直扩展的方法 - An Approach for Scaling Up/Down IBM MQ Channel Throughput
- xcode项目导入github
- 中文 iOS/Mac 开发博客列表
- leetcode 290:Word Pattern
- Activity入门
- ajax 封装
- for each循环使用说明
- 【机器学习】Matlab中实现QQ-plot的一个好工具gqqplot
- Request异步请求处理PART2
- shell中的循环结构
- Python中的字典(dict)
- ffmpeg工作流程分析-3