290. Word Pattern

105人阅读 评论(0)

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:

1. pattern = "abba", str = "dog cat cat dog" should return true.
2. pattern = "abba", str = "dog cat cat fish" should return false.
3. pattern = "aaaa", str = "dog cat cat dog" should return false.
4. 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.

note：

class Solution {
public:
bool wordPattern(string pattern, string str) {

map<char, int> pat;
map<string, int> st;
int i = 0;
int n = pattern.size();
istringstream in(str);  //从字符串中分离出单词

for(string word; in >> word; ++i){  //in >> word 调用in函数，将每个单词赋给word变量
if(i==n || pat[pattern[i]] != st[word]){
return false;
}
pat[pattern[i]] = st[word] = i+1;
}

return i==n;
}
};

java版：利用字符串api处理字符串

public class Solution {
public boolean wordPattern(String pattern, String str) {

String[] words = str.split(" ");
if(words.length != pattern.length()){
return false;
}
Map index = new HashMap();
for(Integer i=0; i<words.length; ++i){
if(index.put(pattern.charAt(i), i) != index.put(words[i], i)){
return false;
}
}

return true;
}
}


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：49449次
• 积分：917
• 等级：
• 排名：千里之外
• 原创：8篇
• 转载：242篇
• 译文：0篇
• 评论：5条
文章分类
阅读排行