74.Isomorphic Strings
来源:互联网 发布:免费申请域名的步骤 编辑:程序博客网 时间:2024/04/30 06:02
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.
分析:题目的关键是理解透彻。判断两个字符串是否为同构的结果就是两个字符串中的字符一一对应。相似的题目是:Word Pattern
我把sc作为key,tc作为value放到map中。当key在map中已存在,则需要取出其对应的value看与目前读到的tc是否一样,一样则继续,不一样则返回false;如果key在map中不存在,则需要看tc是否已作为value值存在map中,若有则说明map中有其他key与tc对应,返回false(如字符串为abcd和ffff),如果tc目前没有作为value值存在map中,则把<sc,tc>放到map中。
/** * 题目要求判断两个字符串是否为同构字符串。也就是说两个字符串之间的字符是否一一对应。 * 首先判断两个字符串的长度是否相等,如果不相等,则返回false。否则继续。 * Step1:依次读s和t中的每个字符,如果sc没有在map中,则首先判断tc是否作为value值已被map中的其他关键字映射,如果是则返回false, * 否则把<sc,tc>放到map中。 * Step2:如果sc在map中,则判断map中对应的值与tc是否一样,相同则继续,不相同的则返回false。 */public boolean isIsomorphic(String s, String t) {if(s.length() != t.length()){return false;}else{int len = s.length();Map<Character, Character> map = new HashMap<Character, Character>();for(int i =0;i<len;i++){char sc = s.charAt(i);char tc = t.charAt(i);/*map中不包含关键字:则首先判断tc是否作为value值已被map中的其他关键字映射,如果是则返回false,否则把<sc,tc>放到map中。*/if(!map.containsKey(sc)){if(map.containsValue(tc)){return false;}else{map.put(sc, tc);}}else{/*map中已包含关键字:判断map中对应的值与tc是否一样,相同则继续,不相同的则返回false。 */char oldc = map.get(sc);if(oldc != tc){return false;}}}return true;} }
- 74.Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- Isomorphic Strings
- 在github上的贡献图里画出你想要的图形
- YTU 1011: Rails
- linux下udp编程
- bluestacks启动问题
- GCC-问题-链接库链上了仍存在"undefined reference to"?
- 74.Isomorphic Strings
- 5-8 UVA 230 Borrowers图书管理系统
- 十步完全理解SQL
- 什么是XML?
- 数据结构与算法——在一个数组中实现两个堆栈(C语言)
- How to building OpenSSL 0.9.8c
- poj2386
- 2015年第六届蓝桥杯C/C++程序设计本科B组省赛 奖券数目(结果填空)
- wordpress禁用scandir引起的错误