290. Word Pattern
来源:互联网 发布:iphone连mac导照片 编辑:程序博客网 时间:2024/06/09 15:01
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.
3ms 19.10%
public class WordPattern {public static boolean wordPattern(String pattern, String str) {String[] strs = str.split(" ");if (pattern.length() != strs.length)return false;Map<Character, String> map = new HashMap<Character, String>();for (int i = 0; i < pattern.length(); i++) {if (!map.containsKey(pattern.charAt(i))) {if (map.containsValue(strs[i]))return false;map.put(pattern.charAt(i), strs[i]);} else {if (strs[i].equals(map.get(pattern.charAt(i))))continue;elsereturn false;}}return true;}}
solution2
3ms 19.10%
This method used the property of the put method of HashMap, if the key has been existed in the map, the new value is going to replace the old value and the returns the old value, if the key was not in the map, put method returns null
public static boolean wordPattern2(String pattern, String str) { if (pattern.isEmpty() || str.isEmpty()) { return false; } String[] s = str.split(" "); if (s.length != pattern.length()) { return false; } @SuppressWarnings("rawtypes") HashMap<Comparable, Integer> hashMap = new HashMap<Comparable, Integer>(); for (int i = 0; i < pattern.length(); i++) { if (!Objects.equals(hashMap.put(pattern.charAt(i), i), hashMap.put(s[i], i))) return false; } return true; }
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
- Python渗透测试工具合集
- shtaPeuqinU.62
- 实现自己的print
- HTML5页面嵌入APP不能正常显示解决方案
- 《Linux Shell 脚本攻略》学习记录之三
- 290. Word Pattern
- Android支付宝支付步骤简述
- chroot
- 浅析Java虚拟机结构与机制
- 函数指针简介
- Java面向抽象编程
- UIAutomator定位Android控件的方法实践和建议(Appium姊妹篇)
- 查询数据库指定表是否存在
- 有了C盘之后,添加另外一个磁盘的方法