java图形找规律题_LeetCode简单题:290. 单词规律(Python,C++,Java)

一.解法

https://leetcode-cn.com/problems/word-pattern/

要点:hashmap

Python,C++,Java都用了相同的哈希表法。

用hashmap对vectorarr和string pattern进行来回两次哈希映射(string映射char以及char映射string),如果都没问题说明单词规律一样。

注意:需要用到split函数,C++中没有split函数需要自己手动写。

二.Python实现

class Solution:

def wordPattern(self, pattern: str, str: str) -> bool:

mp={}

pm={}

wordList=str.split(' ')

if len(pattern)!=len(wordList):

return False

for i in range(len(pattern)):

if pm.get(pattern[i]):

if pm[pattern[i]]!=wordList[i]:

return False

else:

pm[pattern[i]]=wordList[i]

if mp.get(wordList[i]):

if mp[wordList[i]]!=pattern[i]:

return False

else:

mp[wordList[i]]=pattern[i]

return True

三.C++实现

class Solution {

public:

bool wordPattern(string pattern, string str) {

unordered_map mp;

unordered_map pm;

int j=0;

vectorarr;

for(int i=0;i

if(i==str.size()-1){

arr.push_back(str.substr(j,str.size()-j));

}

if(str[i]==' '){

arr.push_back(str.substr(j,i-j));

j=i+1;

}

}

if(pattern.size()!=arr.size()) return false;

int length=pattern.size();

for(int i=0;i

if(mp.find(pattern[i])!=mp.end()&&mp[pattern[i]]!=arr[i]) return false;

if(pm.find(arr[i])!=pm.end()&&pm[arr[i]]!=pattern[i]) return false;

mp[pattern[i]]=arr[i];

pm[arr[i]]=pattern[i];

}

return true;

}

};

四.java实现

class Solution {

public boolean wordPattern(String pattern, String str) {

Map map = new HashMap();

Map map2 = new HashMap();

String[] strs = str.split(" ");

char[] cs = pattern.toCharArray();

if(cs.length != strs.length) return false;

for(int i = 0; i < cs.length;i++){

if(map.containsKey(cs[i])){

if(!map.get(cs[i]).equals(strs[i])) return false;

}

else{ map.put(cs[i],strs[i]);}

if(map2.containsKey(strs[i])){

if(!map2.get(strs[i]).equals(cs[i])) return false;

}

else{map2.put(strs[i],cs[i]);}

}

return true;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值