Isomorphic Strings
2015-05-29 10:04
387 查看
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
return true.
Given
return false.
Given
return true.
Note:
You may assume both s and t have the same length.
思路:用一个hash表来存储两个字符串中字符的映射关系,当出现的字符已经在hash表中出现过,但映射关系与在hash表中原有的映射关系不同时,说明字符串不是同构的,但是也要注意万一出现两个字符映射到同一个字符,比如“ab” 和“aa” 中a和b映射同时映射到a,先把<a,a>放入hash表中,当遍历到b字符的时候,先判断hash表中有没有出现key为b的情况,很显然还没出现过,然后再判断hash表中value有没有出现过a,如果出现了说明已经有字符映射到a了,此时出现某个字符和b映射到同一个字符的情况,说明两个字符串不是同构的。
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.
思路:用一个hash表来存储两个字符串中字符的映射关系,当出现的字符已经在hash表中出现过,但映射关系与在hash表中原有的映射关系不同时,说明字符串不是同构的,但是也要注意万一出现两个字符映射到同一个字符,比如“ab” 和“aa” 中a和b映射同时映射到a,先把<a,a>放入hash表中,当遍历到b字符的时候,先判断hash表中有没有出现key为b的情况,很显然还没出现过,然后再判断hash表中value有没有出现过a,如果出现了说明已经有字符映射到a了,此时出现某个字符和b映射到同一个字符的情况,说明两个字符串不是同构的。
public class Solution { public boolean isIsomorphic(String s, String t) { HashMap<Character,Character> hs=new HashMap<Character,Character>(); int slength=s.length(); int tlength=t.length(); if(slength!=tlength) return false; for(int i=0;i<slength;i++) { if(hs.containsKey(s.charAt(i))) { char ch=hs.get(s.charAt(i)); if(ch!=t.charAt(i)) return false; } else if(hs.containsValue(t.charAt(i))) return false; else hs.put(s.charAt(i),t.charAt(i)); } return true; } }
相关文章推荐
- ABAP性能优化之使用二分查找(Binary Search)选项
- Shiro学习笔记(4)——ini 配置
- cygwin安装
- TFS扩展开发中遇到的坑
- jquery倒计时插件用法
- C++学习 Boost状态机说明statechart
- ModelMap和ModelAndView的区别
- hdu1541 Stars
- ABAP性能优化之向内表添加纪录
- springMVC中文乱码问题
- C++读取系统当前时间
- javaScript判断鼠标滚轮的上下滚动
- oracle游标用法
- 【vim】简介与基本配置
- C++读取系统当前时间 分类: C/C++ 2015-05-29 10:03 47人阅读 评论(0) 收藏
- 10 程序员必备:Linux日常维护命令
- Netty那点事(四)Netty与Reactor模式
- demopu告诉你nginx+php 出现404错误解决方法
- 社説 20150529 対「イスラム国」 国際包囲網の強化が急務だ
- 社説 20150529 五輪専任相 新国立競技場への不信を拭え