目录
290. 单词规律 Word Pattern
291. 单词规律 II Word Pattern ii
每日一练刷题专栏
Rust每日一练 专栏
Golang每日一练 专栏
Python每日一练 专栏
C/C++每日一练 专栏
Java每日一练 专栏
去南京两天,占坑后补
给定一种规律 pattern
和一个字符串 s
,判断 s
是否遵循相同的规律。
这里的 遵循 指完全匹配,例如, pattern
里的每个字母和字符串 str
中的每个非空单词之间存在着双向连接的对应规律。
示例1:
输入: pattern = "abba", str = "dog cat cat dog" 输出: true
示例 2:
输入:pattern = "abba", str = "dog cat cat fish" 输出: false
示例 3:
输入: pattern = "aaaa", str = "dog cat cat dog" 输出: false
提示:
1 <= pattern.length <= 300
pattern
只包含小写英文字母1 <= s.length <= 3000
s
只包含小写英文字母和 ' '
s
不包含 任何前导或尾随对空格s
中每个单词都被 单个空格 分隔代码1:
package main
import (
"fmt"
"strings"
)
func wordPattern(pattern string, s string) bool {
words := strings.Split(s, " ")
if len(pattern) != len(words) {
return false
}
p2s := make(map[byte]string)
s2p := make(map[string]byte)
for i := 0; i < len(pattern); i++ {
p, w := pattern[i], words[i]
if s, ok := p2s[p]; ok {
if s != w {
return false
}
} else {
if _, ok := s2p[w]; ok {
return false
}
p2s[p] = w
s2p[w] = p
}
}
return true
}
func main() {
pattern := "abba"
s := "dog cat cat dog"
fmt.Println(wordPattern(pattern, s))
pattern = "abba"
s = "dog cat cat fish"
fmt.Println(wordPattern(pattern, s))
pattern = "aaaa"
s = "dog cat cat dog"
fmt.Println(wordPattern(pattern, s))
}
代码2:
package main
import (
"fmt"
"strings"
)
func wordPattern(pattern string, s string) bool {
words := strings.Split(s, " ")
if len(pattern) != len(words) {
return false
}
p2s := make(map[byte]string)
used := make(map[string]bool)
for i := 0; i < len(pattern); i++ {
p, w := pattern[i], words[i]
if s, ok := p2s[p]; ok {
if s != w {
return false
}
} else {
if used[w] {
return false
}
p2s[p] = w
used[w] = true
}
}
return true
}
func main() {
pattern := "abba"
s := "dog cat cat dog"
fmt.Println(wordPattern(pattern, s))
pattern = "abba"
s = "dog cat cat fish"
fmt.Println(wordPattern(pattern, s))
pattern = "aaaa"
s = "dog cat cat dog"
fmt.Println(wordPattern(pattern, s))
}
输出:
true
false
false
代码:
go
输出:
✨ 持续,努力奋斗做强刷题搬运工!
点赞,你的认可是我坚持的动力!
收藏,你的青睐是我努力的方向!
✎ 评论,你的意见是我进步的财富!
☸ 主页:https://hannyang.blog.csdn.net/
Rust每日一练 专栏(2023.5.16~)更新中... |
|
Golang每日一练 专栏(2023.3.11~)更新中... |
|
Python每日一练 专栏(2023.2.18~2023.5.18)暂停更 |
|
C/C++每日一练 专栏(2023.2.18~2023.5.18)暂停更 |
|
Java每日一练 专栏(2023.3.11~2023.5.18)暂停更 |