[LeetCode] Isomorphic Strings
来源:互联网 发布:知乎和天涯的区别 编辑:程序博客网 时间:2024/06/10 23:21
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.
思路:
1、使用hash table;
2、将 s 中的字符和 t 中的字符建立映射关系:按照字符出现的顺序依次建立映射,且一个字符只能映射一个字符。故映射关系中键和值都是唯一的
3、如 foo, bar中, f -- b, o -- a, o -- r ,同一个 o 映射两个字符,所以不符合条件;
Java 和 C++实现:
public class Solution { public boolean isIsomorphic(String s, String t) { Map<String, String> myMap = new HashMap<String, String>();for(int i = 0; i < s.length(); i ++){String tmps = s.substring(i, i+1) ;String tmpt = myMap.get(tmps) ;if(tmpt != null){if(!tmpt.equals(t.substring(i, i+1))) return false ;}else{if(myMap.containsValue(t.substring(i, i+1))) return false ;myMap.put(s.substring(i, i+1), t.substring(i, i+1)) ;}}return true ; }}
class Solution {public: bool isIsomorphic(string s, string t) { if(s == "" && t == "") return true ; map<char, char> mymap ;for(int i = 0; i < s.size(); i ++){if(mymap.find(s[i]) != mymap.end()){if(mymap[s[i]] != t[i]) return false ;}else{map<char, char>::iterator p ;for(p = mymap.begin(); p != mymap.end(); p ++){if(p->second == t[i]) return false ;}mymap[s[i]] = t[i];}} }};
0 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
- 花生壳动态域名不在线怎么办
- 数据分区存放到文件中
- iOS - 获取当天的时间段
- 力所能及之hibernate备忘录
- 第12周 项目二-摩托车继承自行车和机动车
- [LeetCode] Isomorphic Strings
- 电脑文件备份软件
- 贵州3女生放学路上被山洪冲走 2人遇难1人失踪
- LINUX下C语言连接mysql
- 【node.js】本地模式安装express:'express' 不是内部或外部命令,也不是可运行的程序或批处理文件
- 同样的Python代码在PyCharm和Pydev里面的运行结果不一致
- Velocity官方指南-Velocity是如何工作的
- Eclipse如何修改Web项目的名称
- Longest Common Prefix