LeetCode-Word Pattern
Posted LiBlog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-Word Pattern相关的知识,希望对你有一定的参考价值。
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.
Credits:
Special thanks to @minglotus6 for adding this problem and creating all test cases.
Solution:
public class Solution { public boolean wordPattern(String pattern, String str) { if (str.isEmpty() && pattern.isEmpty()) return true; if (str.isEmpty() || pattern.isEmpty()) return false; String[] map = new String[26]; Arrays.fill(map,""); String[] words = str.split(" "); HashSet<String> assigned = new HashSet<String>(); if (pattern.length()!=words.length) return false; for (int i=0;i<pattern.length();i++){ char code = pattern.charAt(i); if (!map[code-‘a‘].isEmpty()){ // code.word != word, it is wrong if (!map[code-‘a‘].equals(words[i])){ return false; } } else { // code.word is empty but word has been assigned to another code, it is wrong. if (assigned.contains(words[i])){ return false; } assigned.add(words[i]); map[code-‘a‘] = words[i]; } } return true; } }
以上是关于LeetCode-Word Pattern的主要内容,如果未能解决你的问题,请参考以下文章
csharp C#代码片段 - 使类成为Singleton模式。 (C#4.0+)https://heiswayi.github.io/2016/simple-singleton-pattern-us