今天继续刷LeetCode,第290题,判断两个字符串模式是否相等。
分析:
通过istringstream将第二个字符串的每个单词进行分开,同时比较两个字符串中对应位置map映射的结果是否相等。如果相等,就重新赋值,不等就返回false。
问题:
1、map映射的使用;
2、set的使用;
3、Python中zip的使用。
附上C++代码:
class Solution {
public:
bool wordPattern(string pattern, string str) {
map<char,int> p2i;
map<string,int> s2i;
istringstream in(str);
int i=0,n=pattern.size();
for(string word;in>>word;i++)
{
if(i==n||p2i[pattern[i]]!=s2i[word])
return false;
p2i[pattern[i]]=s2i[word]=i+1;
}
return i==n;
}
};
附上Python代码:
class Solution:
def wordPattern(self, pattern: str, str: str) -> bool:
p=len(pattern)
t=len(str.split())
return p==t and len(set(pattern))==len(set(str.split())) and len(set(pattern))==len(set(zip(pattern,str.split())))
本文解析了LeetCode第290题,判断两个字符串模式是否相等的问题,详细介绍了C++和Python的解决方案,包括map和set的使用,以及Python中zip函数的应用。
2225

被折叠的 条评论
为什么被折叠?



