Leetcode Word Pattern
来源:互联网 发布:哪个搜索软件好 编辑:程序博客网 时间:2024/04/26 00:42
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.
Difficulty: Easy
Solution: HashMap
public class Solution { public boolean wordPattern(String pattern, String str) { HashMap<String, Character> map = new HashMap<String, Character>(); int index = 0, i = 0; for(i = 0; i < pattern.length(); i++){ int start = index; if(index == str.length()) break; while(index < str.length() && str.charAt(index) != ' '){ index++; } String temp = str.substring(start, index); if(!map.containsKey(temp)){ if(map.containsValue(pattern.charAt(i))) return false; map.put(temp, pattern.charAt(i)); } else{ if(map.get(temp) != pattern.charAt(i)){ return false; } } if(index < str.length() && str.charAt(index) == ' ') index++; } if(i != pattern.length() || index!=str.length()) return false; return true; }}
0 0
- leetcode | Word Pattern
- 【leetcode】290. Word Pattern
- leetcode 290: Word Pattern
- [Leetcode]Word Pattern
- [leetcode 290]Word Pattern
- LeetCode 290 Word Pattern
- 【leetcode】290. Word Pattern
- [LeetCode 290] Word Pattern
- leetcode 290 Word Pattern
- LeetCode 2 Word Pattern
- leetcode word-pattern
- leetcode: Word Pattern
- leetcode:Word Pattern
- [Leetcode]Word Pattern
- LeetCode Word Pattern
- LeetCode-Word Pattern
- LeetCode:Word Pattern
- leetcode之Word Pattern
- 一个炫酷的对话框依赖库
- 推挽结构详解
- Java多线程 之 ThreadPoolExecutor(九)
- Android stadio 自定义debug release keystore
- volley网络请求保持sessionID
- Leetcode Word Pattern
- [LC260]Single Number III
- Socket相关函数解析
- 七大排序
- Python 核心编程笔记_Chapter_2 Note_3_赋值与变量_字符串_列表list_元组tuple_字典dict
- iOS直播技术分析与实现
- HDOJ 3430 Shuffling
- Android&&Unity交互——同一个apk
- 大一数据库系统概论期末复习参考