290. Word Pattern
来源:互联网 发布:centos虚拟机不能上网 编辑:程序博客网 时间:2024/05/16 10:17
290. Word Pattern
Given a pattern
and a stringstr
, find ifstr
follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter inpattern
and anon-empty word instr
.
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, andstr
contains lowercase letters separated by a single space.
这个题就是说判断是否字符串pattern中的每个元素与str中的每个元素存在一一对应的关系,即不同的KEY对应不同的VALUE,不太习惯用Map首先是用Vector实现的:
class Solution {public:bool wordPattern(string pattern, string str) {str = str + " ";string t;vector<string> s;for (int i = 0; i < str.size(); i++) {if (str[i] != ' ') t = t + str[i];else{s.push_back(t);t = "";}}if (pattern.size() != s.size()) return 0;for (int i = 0; i < pattern.size()-1; i++) {for (int j = i+1; j < pattern.size(); j++) {if (pattern[i] != pattern[j] && s[i] == s[j]) return 0;else if (pattern[i] == pattern[j] && s[i] != s[j]) return 0;}}return 1;}};
就是将str存入字符数组s中,通过比较是否有一一对应关系得出结果。
然后看了大神的代码:
bool wordPattern(string pattern, string str) {map<char, int> p2i;map<string, int> w2i;istringstream in(str);int i = 0, n = pattern.size();for (string word; in >> word; ++i) {if (i == n || p2i[pattern[i]] != w2i[word])return false;p2i[pattern[i]] = w2i[word] = i + 1;}return i == n;}确实很巧妙,通过两个Map来实现一一对应的关系。还是用Map简单。
0 0
- 【leetcode】290. Word Pattern
- 【leetcode】290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern LeetCode
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- 290. Word Pattern
- Leetcode 290. Word Pattern
- 290. Word Pattern
- 【LeetCode】290. Word Pattern
- 290. Word Pattern
- LeetCode-290. Word Pattern
- LeetCode *** 290. Word Pattern
- 史上最全的SQL Server复习笔记一
- C#学习日记 Type类
- RecyclerView的基本用法
- ambari && HDP
- CSUOJ 1005 Binary Search Tree analog(二叉搜索树模拟)
- 290. Word Pattern
- openH264参数总结
- 数据库-MySQL安装及使用
- Webstrom 使用过程中遇到的问题以及解决方案
- ReactNative的Navigator组件使用方式
- UUID解析与使用
- TextView的常用属性
- 测试数据库最多连接数
- linux密码故障解决