[LeetCode] Word Pattern
来源:互联网 发布:电脑软件快捷键冲突 编辑:程序博客网 时间:2024/05/18 09:20
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.
解题思路
- 用一个哈希表建立从pattern中字符到str中字符串的映射。
- 用一个集合表示str中字符串是否已作为值出现在哈希表中。
以下两种情况为假:- 哈希表中已存在key,但是对应的value值不一样。
- 哈希表中不存在key,但是对应的值已作为其他key的value值。
实现代码
C++:
// Runtime: 0 msclass Solution {public: bool wordPattern(string pattern, string str) { vector<string> words; istringstream iss(str); string temp; while (iss>>temp) { words.push_back(temp); } if (words.size() != pattern.size()) { return false; } unordered_map<char, string> mymap; set<string> used; for (int i = 0; i < pattern.length(); i++) { if (mymap.find(pattern[i]) == mymap.end()) { if (used.find(words[i]) == used.end()) { mymap[pattern[i]] = words[i]; used.insert(words[i]); } else { return false; } } else if (mymap[pattern[i]].compare(words[i]) != 0) { return false; } } return true; }};
Java:
// Runtime: 3 mspublic class Solution { public boolean wordPattern(String pattern, String str) { String words[] = str.split(" "); if (pattern.length() != words.length) { return false; } Map<Character, String> mymap = new HashMap<Character, String>(); for (int i = 0; i < pattern.length(); i++) { if (!mymap.containsKey(pattern.charAt(i))) { if (!mymap.containsValue(words[i])) { mymap.put(pattern.charAt(i), words[i]); } else { return false; } } else if (!mymap.get(pattern.charAt(i)).equals(words[i])) { return false; } } return true; }}
1 0
- leetcode | Word Pattern
- 【leetcode】290. Word Pattern
- leetcode 290: Word Pattern
- [Leetcode]Word Pattern
- [leetcode 290]Word Pattern
- LeetCode 290 Word Pattern
- 【leetcode】290. Word Pattern
- [LeetCode 290] Word Pattern
- leetcode 290 Word Pattern
- LeetCode 2 Word Pattern
- leetcode word-pattern
- leetcode: Word Pattern
- leetcode:Word Pattern
- [Leetcode]Word Pattern
- LeetCode Word Pattern
- LeetCode-Word Pattern
- LeetCode:Word Pattern
- leetcode之Word Pattern
- redis数据结构
- ibatis 中$field$与#field#的区别
- 字符char的转换
- 如何查找苹果API
- 生成二维码,微信分享
- [LeetCode] Word Pattern
- Visual Studio 2015 的安装和使用
- React Native
- Hadoop学习笔记之<输入格式>
- java基础学习笔记——网络UDP/聊天
- 毫秒必争,前端网页性能最佳实践
- XML之DOM解析
- redis内存优化
- 成员变量的形式(int)