LeetCode(44)- Isomorphic Strings
2016-04-11 16:07
423 查看
题目:
Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. For example, Given "egg", "add", return true. Given "foo", "bar", return false. Given "paper", "title", return true. Note: You may assume both s and t have the same length.
思路:
题意:给定两个同样长度的字符串,判断这两个字符串是不是同形,所谓同形就是,两个字符串相等的地方一样,如上面举例的字符串。可以利用判断字符串是不是有重复字符的思路,把字符串转化为数组,存进hashMap,判断是否有重复值,有了判断相应的坐标是不是相同,不相同,或者不同时出现重复,均为不满足条件。出现重复,去掉重复,添加新元素,不重复,只是添加新元素。
-
代码:
public class Solution { public boolean isIsomorphic(String s, String t) { if(s == null){ return true; } char[] a = s.toCharArray(); char[] b = t.toCharArray(); int n = a.length; Map<Character,Integer> aa = new HashMap<Character,Integer>(); Map<Character,Integer> bb = new HashMap<Character,Integer>(); for(int i = 0;i < n;i++){ if(aa.containsKey(a[i])){ if(!bb.containsKey(b[i])){ return false; }else{ int c = aa.get(a[i]); int d = bb.get(b[i]); if(c != d){ return false; }else{ aa.remove(a[i]); bb.remove(b[i]); aa.put(a[i],i); bb.put(b[i],i); } } }else{ if(bb.containsKey(b[i])){ return false; }else{ aa.put(a[i],i); bb.put(b[i],i); } } } return true; } }
相关文章推荐
- LeetCode(44)- Isomorphic Strings
- 关于TCP的一些零散知识
- android 设置app版本号
- 浏览器 HTTP 协议缓存机制详解
- FOJ Problem 2214 Knapsack problem
- linux centos6.5 64位 安装nginx
- GitHub 书写 readme
- 使用Spring Security保护web应用安全
- VS2013中Python学习笔记[环境搭建]
- android中jsoup解析html的几个例子
- JS需要注意的细节和一些基础知识
- java Reentrant Lock
- CSS3学习系列之颜色
- iOS通知中心升级 -可设置按优先级执行block
- 集合之HashSet
- url-pattern匹配规则
- MySQL Master-Slave Replication
- iTOP-4418嵌入式开发板接口基本介绍
- 欢迎使用CSDN-markdown编辑器
- HDU 3836 —— Equivalent Sets