《leetCode》:Isomorphic Strings
来源:互联网 发布:关于知乎的诗词 编辑:程序博客网 时间:2024/05/20 16:33
题目
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即可完成,但是要注意的是:Map虽然保证了键的唯一,但是我们还要保证键值中的值唯一,即不可以有多个键对应 一个值。
public boolean isIsomorphic(String s, String t) { if(s==null&&t==null){ return true; } int len1=s.length(); int len2=t.length(); if(len1!=len2){ return false; } Map<Character,Character> map=new HashMap<Character,Character>(); StringBuffer sb=new StringBuffer(); for(int i=0;i<len1;i++){ char ch=map.getOrDefault(s.charAt(i), '\0'); if(ch=='\0'){//第一次出现,则保存 //保存之前要检查,键值中的值是否唯一,即不能多个不同的键映射到一个值 char tempCh=t.charAt(i); if(map.containsValue(tempCh)){ return false; } map.put(s.charAt(i),tempCh);//只有键和值都没有出现,才加入map sb.append(tempCh); } else{ sb.append(ch); } } if(t.equals(sb.toString())){ return true; } return false; }
1 0
- LeetCode 205 - Isomorphic Strings
- [LeetCode] Isomorphic Strings
- Isomorphic Strings Leetcode JAVA
- [LeetCode] Isomorphic Strings
- [LeetCode 205]Isomorphic Strings
- LeetCode 205-Isomorphic Strings
- leetcode Isomorphic Strings
- leetcode(c++) Isomorphic Strings
- leetcode--Isomorphic Strings
- [LeetCode]Isomorphic Strings
- LeetCode OJ Isomorphic Strings
- leetcode 205: Isomorphic Strings
- leetcode 205 Isomorphic Strings
- [leetcode] Isomorphic Strings
- 【leetcode】Isomorphic Strings
- [leetcode]Isomorphic Strings
- [LeetCode]Isomorphic Strings
- leetcode--Isomorphic Strings
- ....
- CEGUI自定义控件的几个关键步骤
- HDOJ 2058 The sum problem
- socket编程UDP小例子
- 使用 Shell 脚本自动化 Linux 系统维护任务
- 《leetCode》:Isomorphic Strings
- Java深克隆和浅克隆的原理及实现
- POJ 3768 Repeater
- Git远程操作详解
- iOS如何上传代码到Github
- 三种ViewController跳转的异同(两种转场动画的实现待总结)
- 【Linux学习】epoll详解
- ZooKeeper的工作流程
- UVa 679 Dropping Balls