博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode:Word Pattern
阅读量:7015 次
发布时间:2019-06-28

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

problem:

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:

  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. 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  for adding this problem and creating all test cases.

 

 to see which companies asked this question

Solution:

 

public class Solution {    public boolean wordPattern(String pattern, String str) {        if (pattern.isEmpty() || str.isEmpty()) {            return false;        }                 String[] s = str.split(" ");        if (s.length != pattern.length()) {            return false;        }                 HashMap
hashMap = new HashMap
(); for (int i = 0; i < pattern.length(); i++) { if (hashMap.containsKey(pattern.charAt(i))) { if (!hashMap.get(pattern.charAt(i)).equals(s[i])) { return false; } } else if (hashMap.containsValue(s[i])) { return false; } else { hashMap.put(pattern.charAt(i), s[i]); } } return true; }}

 

转载于:https://www.cnblogs.com/xiaoying1245970347/p/5178433.html

你可能感兴趣的文章
python内建函数
查看>>
Sencha-数据-Proxy(代理) (官网文档翻译25)
查看>>
[C#]richtextbox实现拖放
查看>>
Python ImportError: cannot import name *
查看>>
Hadoop生态圈-Flume的组件之拦截器与选择器
查看>>
Java基础-SSM之mybatis多对多关联
查看>>
Android微信支付SDK开发
查看>>
[Android Pro] 横竖屏切换时,禁止activity重新创建,android:configChanges="keyboardHidden|orientation" 不起作用...
查看>>
上学路线
查看>>
相对路径 System.Web HttpServerUtilityBase Server.MapPath("~/")
查看>>
【转】Spring中事务与aop的先后顺序问题
查看>>
IIS服务器管理学习
查看>>
poj3252-Round Number 组合数学
查看>>
程序猿和星座之间不可不谈的事
查看>>
log4j.properties 日志分析
查看>>
pdfminer import报错解决方法
查看>>
测试用例大全
查看>>
装饰者模式
查看>>
如何修改WAMP中mysql默认空密码
查看>>
Java内存区域和GC机制篇
查看>>