Easy-题目46:205. Isomorphic Strings
来源:互联网 发布:mac如何卸载opera 编辑:程序博客网 时间:2024/06/04 18:11
题目原文:
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,判断他们是不是同构(isomorphic)的。
同构的定义是s和t具有相同的结构,即可用t串一个字符代替s串的一个字符,而其他字符不变。
例如,”egg”和 ”add”是同构的;”foo”和”bar”不是同构的;”paper”和”title ”是同构的。
保证s串和t串的长度相等。
题目分析:
使用一个HashMap记录一组key-value对,key为s串中每个字符,value为t串中每个字符。如果出现相同的key则不是同构的。
例如s=”foo”,t=”bar”,则存在o-b和o-r两个同key的映射。
但这样还不够,还要再按相同方法建立t串到s串的map,因为若s=”bar”,t=”foo”则不存在s串到t串中的相同key,但存在t串到s串的相同key。
源码:(language:java)
public class Solution { public boolean isIsomorphic(String s, String t) { int slen=s.length(); int tlen=t.length(); if(slen!=tlen) return false; else { HashMap<Character,Character> map=new HashMap(); for(int i=0;i<slen;i++) { if(!map.containsKey(s.charAt(i))) map.put(s.charAt(i),t.charAt(i)); else { if(map.get(s.charAt(i)) != t.charAt(i)) return false; } } map.clear(); for(int i=0;i<slen;i++) { if(!map.containsKey(t.charAt(i))) map.put(t.charAt(i),s.charAt(i)); else { if(map.get(t.charAt(i)) != s.charAt(i)) return false; } } return true; } }}
成绩:
34ms,beats 30.09%,众数26ms,8.93%
- Easy-题目46:205. Isomorphic Strings
- 205. Isomorphic Strings [easy] (Python)
- Leetcode 205. Isomorphic Strings (Easy) (cpp)
- Letcode 205[easy]--- Isomorphic Strings. Isomorphic Strings
- [Leetcode 205, Easy] Isomorphic Strings
- Easy 205题 Isomorphic Strings
- 205.leetcode Isomorphic Strings (easy)[map结构 字符串处理]
- <LeetCode><Easy> 205 Isomorphic Strings --HashTable
- 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
- Easy-题目45:58. Length of Last Word
- [Maven]5,相关配置
- Java性能提高小常识
- 怎么快速看懂别人写的module和ipcore
- Android基础知识整合篇——Activity知识点
- Easy-题目46:205. Isomorphic Strings
- 鼠标经过旋转特效
- 神经网络浅析
- 【HDU】 1431 素数回文
- new一个对象的过程
- Package.json中dependencies依赖包中^符号和~符号前缀的区别
- Easy-题目47:20. Valid Parentheses
- 百度地图api
- VS2015找不到stdlib.h的问题