Lettcode_205_Isomorphic Strings,isomorphicstrings
本文是在學習中的總結,歡迎轉載但請註明出處:http://blog.csdn.net/pistolove/article/details/46530865
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.
思路:
(1)題意為給定兩個長度相同的字串,判斷這兩個字串中相同字元位置上是否相對應。
(2)要判斷相同字元的位置是否相對應,需要記錄所有字元出現的位置。首先,建立兩個不同的Map分別來儲存兩個字串相關資訊,其中key為字串中的字元,value為該字元在字串中的下標(下標以字串形式儲存),例如:egg和add的儲存形式分別為{e={"1"},g={"23"}}和{a={"1"},d={"23"}}。其次,只需要遍曆字元數組中的每一個字元,如果Map對應的key中不包含當前遍曆的字元,則將該字元及其位置存入Map中,否則,則從Map中取出當前字元對應的value,將當前字元位置追加到value上。最後,遍曆完字元數組後,需要判斷兩個Map所對應value大小是否相同,不相同則返回false,否則,分別將兩個Map中value值依次放入兩個新的StringBuffer中,如果最後得到的字串內容相同,則返回true,否則返回false。例如:egg和add最後得到的字串都為“123”,而pick和good對應的Map為{p={"1"},i={"2"},c={"3"},k={"4"}}和{g={"1"},o={"23"},d={"4"}},顯然兩個Map對應value大小不同,所以返回false。
(3)詳情將下方代碼。希望本文對你有所協助。
演算法代碼實現如下:
package leetcode;import java.util.Iterator;import java.util.LinkedHashMap;import java.util.Map;/** * * @author liqq * */public class Isomorphic_Strings {public static boolean isIsomorphic(String s, String t) {char[] ch1 = s.toCharArray();char[] ch2 = t.toCharArray();int len = ch1.length;Map<Character, StringBuffer> _map1 = new LinkedHashMap<Character, StringBuffer>();Map<Character, StringBuffer> _map2 = new LinkedHashMap<Character, StringBuffer>();for (int i = 0; i < len; i++) {if(_map1.get(ch1[i])==null){_map1.put(ch1[i], new StringBuffer());_map1.get(ch1[i]).append(i);}else{_map1.get(ch1[i]).append(i);}if(_map2.get(ch2[i])==null){_map2.put(ch2[i], new StringBuffer());_map2.get(ch2[i]).append(i);}else{_map2.get(ch2[i]).append(i);}if(_map1.values().size()!=_map2.values().size()){return false;}}StringBuffer b1 = new StringBuffer();StringBuffer b2 = new StringBuffer();for (Iterator<StringBuffer> iterator1 = _map1.values().iterator(),iterator2 = _map2.values().iterator(); iterator1.hasNext()&&iterator2.hasNext();) {b1.append(iterator1.next());b2.append(iterator2.next());}return b1.toString().equals(b2.toString());}}