Leetcode_205_Isomorphic Strings

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）题意为给定两个长度相同的字符串，判断这两个字符串中相同字符位置上是否相对应。

（3）详情将下方代码。希望本文对你有所帮助。

package leetcode;

import java.util.Iterator;
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());
}
}


• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120