博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
算法-Hash-单词规律
阅读量:2181 次
发布时间:2019-05-01

本文共 1686 字,大约阅读时间需要 5 分钟。

算法-Hash-单词规律

1 题目概述

1.1 题目出处

https://leetcode-cn.com/problems/word-pattern/

1.2 题目描述

给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。

这里的 遵循 指完全匹配,例如, 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
示例 4:

输入: pattern = “abba”, str = “dog dog dog dog”

输出: false
说明:
你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。

2 HashMap

2.1 思路

  1. 用HashMap存储每个字符串中的单词对应的parrtern中的同位置的字符。
  2. 循环遍历时,每次先用parrtern中的同位置的char和当前位置对应的char对比,如果不同就不对返回false
  3. 随后还要获取同位置的char的上次出现位置,拿到下标信息后去取对应的单词,并和当前单词对比,如果不同也返回false

2.2 代码

class Solution {
public boolean wordPattern(String pattern, String str) {
String[] strs = str.split(" "); char[] pc = pattern.toCharArray(); if(strs.length != pc.length){
return false; } Map
scMap = new HashMap<>(); int[] postion = new int[256]; for(int i = 0; i < pc.length; i++){
char c = pc[i]; String currentStr = strs[i]; Character ch = scMap.get(currentStr); if(ch != null ){
if(c != ch){
return false; } }else{
scMap.put(currentStr, c); } int p = postion[c]; if(p != 0){
String oldStr = strs[p - 1]; if(!oldStr.equals(currentStr)){
return false; } } postion[c] = i + 1; } return true; }}

2.3 时间复杂度

在这里插入图片描述

O(N)

2.4 空间复杂度

O(N)

转载地址:http://glpkb.baihongyu.com/

你可能感兴趣的文章
【雅思】雅思需要购买和准备的学习资料
查看>>
【雅思】雅思写作作业(1)
查看>>
【雅思】【大作文】【审题作业】关于同不同意的审题作业(重点)
查看>>
【Loadrunner】通过loadrunner录制时候有事件但是白页无法出来登录页怎么办?
查看>>
【English】【托业】【四六级】写译高频词汇
查看>>
【托业】【新东方全真模拟】01~02-----P5~6
查看>>
【托业】【新东方全真模拟】03~04-----P5~6
查看>>
【托业】【新东方托业全真模拟】TEST05~06-----P5~6
查看>>
【托业】【新东方托业全真模拟】TEST09~10-----P5~6
查看>>
【托业】【新东方托业全真模拟】TEST07~08-----P5~6
查看>>
solver及其配置
查看>>
JAVA多线程之volatile 与 synchronized 的比较
查看>>
Java集合框架知识梳理
查看>>
笔试题(一)—— java基础
查看>>
Redis学习笔记(三)—— 使用redis客户端连接windows和linux下的redis并解决无法连接redis的问题
查看>>
Intellij IDEA使用(一)—— 安装Intellij IDEA(ideaIU-2017.2.3)并完成Intellij IDEA的简单配置
查看>>
Intellij IDEA使用(二)—— 在Intellij IDEA中配置JDK(SDK)
查看>>
Intellij IDEA使用(三)——在Intellij IDEA中配置Tomcat服务器
查看>>
Intellij IDEA使用(四)—— 使用Intellij IDEA创建静态的web(HTML)项目
查看>>
Intellij IDEA使用(五)—— Intellij IDEA在使用中的一些其他常用功能或常用配置收集
查看>>