205. Isomorphic Strings
来源:互联网 发布:阿里云部署git服务器 编辑:程序博客网 时间:2024/05/16 06:37
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.
题目大意:
给定两个字符串s和t,判断它们是否是同构的。
如果字符串s可以通过字符替换的方式得到字符串t,则称s和t是同构的。
字符的每一次出现都必须被其对应字符所替换,同时还需要保证原始顺序不发生改变。两个字符不能映射到同一个字符,但是字符可以映射到其本身。
测试样例如题目描述。
可以假设s和t等长。
这道题用hashmap 的containskey() 和containsValue() 可以解决。遍历s 或者t,如果hashmap 中含有当前字符,判断另一个字符串的对应位是不是等于之前存储的映射,如果没有当前的字符,则先判断当前映射的value有没有被用过,然后存储当前的key 和value。代码如下:
public class Solution { public boolean isIsomorphic(String s, String t) { HashMap<Character, Character> hs = new HashMap<Character, Character>(); char[] chars = s.toCharArray(); char[] chart = t.toCharArray(); for (int i = 0; i < chars.length; i++) { if (hs.containsKey(chars[i])) { if (chart[i] != hs.get(chars[i])) { return false; } } else { if (hs.containsValue(chart[i])) { return false; } else { hs.put(chars[i], chart[i]); } } } return true; }}下面还有一种思路,用2个256位int数组存s,t各个char值的使用次数,如果是1,1映射,两个256位数组肯定1,1对映,否则不是1,1映射。代码如下:
class Solution {public: bool isIsomorphic(string s, string t) { int m1[256] = {0}, m2[256] = {0}, n = s.size(); for (int i = 0; i < n; ++i) { if (m1[s[i]] != m2[t[i]]) return false; m1[s[i]] = i + 1; m2[t[i]] = i + 1; } return true; }};
- 205. Isomorphic Strings
- 【LeetCode】205.Isomorphic Strings
- [leetcode] 205.Isomorphic Strings
- LeetCode 205. Isomorphic Strings
- 205. Isomorphic Strings
- 205. Isomorphic Strings LeetCode
- 205. Isomorphic Strings
- 205. Isomorphic Strings
- 205. Isomorphic Strings
- 205. Isomorphic Strings
- 205. Isomorphic Strings
- 205. Isomorphic Strings
- 205. Isomorphic Strings
- 【LeetCode】205. Isomorphic Strings
- LeetCode *** 205. Isomorphic Strings
- leetcode 205. Isomorphic Strings
- LeetCode 205. Isomorphic Strings
- 205. Isomorphic Strings
- 需求管理
- 深入oracle分区索引的详解
- Oracle 分区表维护
- 【LeetCode】 338. Counting Bits
- Windows下Tensorflow安装流程
- 205. Isomorphic Strings
- C语言计算日期,前n天,后n天方法
- 80老翁谈人生(314):别了,亲爱的CSDN读者朋友们!
- 【LeetCode】 413. Arithmetic Slices
- Amazon EC2 Instance Express API配置HTTPS
- ZCMU-1787-Babelfish
- Erlang 实现互斥量
- android_39_跳转至第2个Activity
- java常用单词