LeetCode Algorithms #290 <Word Pattern>
来源:互联网 发布:php 房源管理系统 编辑:程序博客网 时间:2024/05/24 03:40
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.
思路:
将str按照空格切割成单词,然后同时遍历str切割后的数组与pattern中的单个字符,确保任意相同下标组合的pattern中的两字母与str切割后的两数组元素是否同时相等或不相等。
没有太多需要注意的,记得检验str切割后的数组元素个数与pattern的字符数是否相同以避免runtime error.
解:
class Solution {public: std::vector<std::string> split(const std::string str, const std::string splitPattern){ std::vector<std::string> result; if(!str.size()) { return result; } size_t splitStart = 0; size_t splitEnd = str.find_first_of(" "); while (splitEnd != str.npos) { result.push_back(str.substr(splitStart, splitEnd - splitStart)); splitStart = splitEnd + 1; splitEnd = str.find_first_of(splitPattern, splitStart); } if(!str.substr(splitStart).empty()) { result.push_back(str.substr(splitStart)); } return result;} bool wordPattern(string pattern, string str) { std::vector<std::string> strChars = split(str, " "); if(strChars.size() != pattern.size()) return false; for(unsigned patternIndex = 0; patternIndex < pattern.size() - 1; patternIndex++) { for(unsigned compareIndex = patternIndex; compareIndex < pattern.size(); compareIndex++) { if(pattern[patternIndex] == pattern[compareIndex] && strChars[patternIndex] != strChars[compareIndex]) return false; if(pattern[patternIndex] != pattern[compareIndex] && strChars[patternIndex] == strChars[compareIndex]) return false; } } return true; }};
0 0
- LeetCode Algorithms #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
- Leetcode NO.125 Valid Palindrome
- 2048最高分
- 循环队列实现
- Android基础——Fragment控制切换(一)
- Android基础之Fragment与Activity交互详解(二)
- LeetCode Algorithms #290 <Word Pattern>
- Android基础之使用Fragment控制切换多个页面(三)
- LeetCode Algorithms #104 <Maximum Depth of Binary Tree>
- *LeetCode-Interleaving String
- File类的基本知识
- LeetCode Algorithms #237<Delete Node in a Linked List>
- hdu5499 SDOI
- 【bzoj2226】【spoj5971】【lcmsum】【数论】
- Android 对话框(Dialog)大全 建立你自己的对话框