leetcode 290: Word Pattern
2015-10-06 16:10
417 查看
Word Pattern
Total Accepted:1733 Total Submissions:
6204 Difficulty: Easy
Given a
patternand a string
str, find if
strfollows the same pattern.
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:
Both
patternand
strcontains only lowercase alphabetical letters.
Both
patternand
strdo not have leading or trailing spaces.
Each word in
stris separated by a single space.
Each letter in
patternmust map to a word with length that is at least 1.
Credits:
Special thanks to
@minglotus6 for adding this problem and creating all test cases.
[思路]
char 和 string 一一对应. 建一个map. 同时set里面保存string, 避免重复, 出现多对1的情况.
[CODE]
public class Solution { public boolean wordPattern(String pattern, String str) { //input check String[] strs = str.split(" "); if(pattern.length() != strs.length ) return false; Map<Character, String> map = new HashMap<>(); Set<String> unique = new HashSet<>(); for(int i=0; i<pattern.length(); i++) { char c = pattern.charAt(i); if(map.containsKey(c) ) { if(!map.get(c).equals(strs[i])) return false; } else { if(unique.contains(strs[i])) return false; map.put(c, strs[i]); unique.add(strs[i]); } } return true; } }
相关文章推荐
- java 中static final关键字
- 如何在控件没有绘制完成之前读取控件的长宽
- Learn more study less 读后感
- 随机数
- 多表联查
- ACM学习历程—POJ3565 Ants(最佳匹配KM算法)
- hdu5117 Fluorescent DP,期望
- 【Scala学习笔记】2. 函数定义、流程控制、异常处理
- eclipse中倒入项目时,报关于.classpath的错误
- JavaBean入门 - 概念和简单例子
- sizeof用法大总结(下)
- Android入门笔记(一)
- The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation. 怎么解决
- 数据库出现 Incorrect key file for table ‘test’; try to repair it
- 线上慢查询的排查
- 怎样写出好代码——设计原则
- Memcached服务器的图形化管理工具
- 有多少个斐波那契子数列(微软笔试题)
- Debian 8 root 远程登录
- android中LayoutInflater.from(context).inflate的分析