LeetCode 205. Isomorphic Strings
来源:互联网 发布:免费时时彩网站源码 编辑:程序博客网 时间:2024/06/10 06:06
题目要求如下
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.
我一开始的思路是只要两个字符串有重复的字母的位置是一样的就是符合要求的,于是写了如下代码
class Solution { public boolean isIsomorphic(String s, String t) { if(s.length()!=t.length()){ return false; } char[]s1=s.toCharArray(); char[]t1=t.toCharArray(); for(int i=0;i<s1.length;i++){ for(int j=i;j<s1.length;j++){ if(s1[i]==s1[j]&&t1[i]!=t1[j]){ return false; } if(t1[i]==t1[j]&&s1[i]!=s1[j]){ return false; } } } return true; }
时间超时了。。。看大神的解法自愧不如。。。
字符串的问题常用字典和HashMap来解决,下面两个解法都很巧妙
public class Solution { public boolean isIsomorphic(String s, String t) { if(s == null || s.length() <= 1) return true; HashMap<Character, Character> map = new HashMap<Character, Character>(); for(int i = 0 ; i< s.length(); i++){ char a = s.charAt(i); char b = t.charAt(i); if(map.containsKey(a)){ if(map.get(a).equals(b)) continue; else return false; }else{ if(!map.containsValue(b)) map.put(a,b);//看ab是不是一一对应 else return false; } } return true; }}
public class Solution { public boolean isIsomorphic(String s1, String s2) { int[] m = new int[512];//相当于建立一个字典 for (int i = 0; i < s1.length(); i++) { if (m[s1.charAt(i)] != m[s2.charAt(i)+256]) return false; m[s1.charAt(i)] = m[s2.charAt(i)+256] = i+1; //记录位置信息 } return true; }}
阅读全文
0 0
- 【LeetCode】205.Isomorphic Strings
- [leetcode] 205.Isomorphic Strings
- LeetCode 205. Isomorphic Strings
- 205. Isomorphic Strings LeetCode
- 【LeetCode】205. Isomorphic Strings
- LeetCode *** 205. Isomorphic Strings
- leetcode 205. Isomorphic Strings
- LeetCode 205. Isomorphic Strings
- LeetCode 205. Isomorphic Strings
- leetcode-205. Isomorphic Strings
- LeetCode-205.Isomorphic Strings
- leetcode 205. Isomorphic Strings
- [leetcode] 205. Isomorphic Strings
- 205.[Leetcode]Isomorphic Strings
- leetcode 205. Isomorphic Strings
- 【leetcode】205. Isomorphic Strings
- [Leetcode]205. Isomorphic Strings
- LeetCode - 205. Isomorphic Strings
- adb命令打开系统设置界面
- hdu1013 Digital Roots
- 将framework 发布到cocoapods
- intellij idea使用指南—— 导入Eclipse的Web项目
- 严重: Exception starting filter struts2 Unable to load configuration
- LeetCode 205. Isomorphic Strings
- 【美团面试】不开辟新的内存空间实现数组去重
- TextView 中SpannableString应用,让你灵活玩转TextView
- LRU缓存实现(Java)
- 数组奇偶划分
- Docker总结(一)
- Surprising Strings
- Jenkins集成.NET操作说明
- PostgreSQL BRIN索引内核代码优化思考