Leetcode Word Pattern
2015-10-06 08:28
405 查看
Given a
Examples:
pattern =
pattern =
pattern =
pattern =
Notes:
Both
Both
Each word in
Each letter in
注意:pattern =
即当map里不包含key 时,还要检查是否已包含Value, 如果已含,那么return false.
另外,分割space 使用str.split("\\s+")
Java code:
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.
解题思路:
使用HashMap, pattern 里的character 对应str 里的word.注意:pattern =
"abba", str =
"dog dog dog dog"should return false.
即当map里不包含key 时,还要检查是否已包含Value, 如果已含,那么return false.
另外,分割space 使用str.split("\\s+")
Java code:
public boolean wordPattern(String pattern, String str) { String[] splited = str.split("\\s+"); if(pattern.length() != splited.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(splited[i])){ return false; } map.put(pattern.charAt(i), splited[i]); }else{ if(!map.get(pattern.charAt(i)).equals(splited[i])){ return false; } } } return true; }
相关文章推荐
- 1>opencv_test1.obj : error LNK2019: 无法解析的外部符号_cvReleaseImage,该符号在函数_main 中被引用
- ios:kvo概述
- const修饰类的成员函数
- Amazon Redshift and Massively Parellel Processing
- Haar特征
- 经方败案群0924高坤锋鼻炎、咳嗽语音发言整理版
- 音频播放AVAudioPlayer后台播放
- HDU 1222 Wolf and Rabbit(数论)
- 执行eclipse,迅速failed to create the java virtual machine。
- Linux高性能server规划——多线程编程(在)
- ZXV10 B700V5机顶盒支持的无线网卡主芯片
- ifree卡黄金版和普通ifree卡的区别
- POJ 3074 解题报告
- 一秒解决直接双击启动tomcat-startup.bat闪退
- 直连网线和交叉网线
- UI初级连载12-------------滑动视图
- this 的用法
- *LeetCode-Find the Duplicate Number
- 揭秘利用互联网营销的全国拍卖骗子公司 - (深圳拍卖公司)
- Matlab Error (Matrix dimensions must agree)