leetcode 290:Word Pattern
2016-04-17 16:50
211 查看
题目描述:
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 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解