标签:
创建两个数组 分别记录两个字符串 各个位置字符出现的上一个位置 通过比较当前字符的上一个位置是否相同 判断是否同构
比较坑爹的是 一开始以为只有字母 所以纠结于怎么找出字母来。。。
代码如下:
public class IsomorphicStrings {
public static boolean isIsomorphic(String s, String t) {
int[] alpha1 = new int[1000];
int[] alpha2 = new int[1000];
for(int i = 0; i < s.length(); i++){
int from_a1 = (int) (s.charAt(i) - ‘a‘);
int from_A1 = (int) (s.charAt(i) - ‘A‘);
int from_a2 = (int) (t.charAt(i) - ‘a‘);
int from_A2 = (int) (t.charAt(i) - ‘A‘);
if(((from_a1 < 0 || from_a1 > 25) && (from_A1 < 0 || from_A1 > 25)) &&
((from_a2 < 0 || from_a2 > 25) && (from_A2 < 0 || from_A2 > 25))){
System.out.print(from_a1 + " ");
System.out.print(from_A1 + " ");
System.out.print(from_a2 + " ");
System.out.print(from_A2 + " ");
System.out.println();
}
else if( ((from_a1 >= 0 && from_a1 <= 25) || (from_A1 >= 0 && from_A1 <= 25)) &&
((from_a2 >= 0 && from_a2 <= 25) || (from_A2 >= 0 && from_A2 <= 25))){
System.out.print(alpha1[from_a1] + " ");
System.out.print(from_a1 + " ");
System.out.print(alpha2[from_a2] + " ");
System.out.print(from_a2 + " ");
System.out.println();
if(alpha1[from_a1] != alpha2[from_a2]) return false;
alpha1[from_a1] = i+1;
alpha2[from_a2] = i+1;
//continue;
}
else return false;
}
return true;
}
无视之
更新后:
public class Solution {
public boolean isIsomorphic(String s, String t) {
int[] alpha1 = new int[128];
int[] alpha2 = new int[128];
for(int i = 0; i < s.length(); i++){
int from_a1 = (int) (s.charAt(i));
int from_a2 = (int) (t.charAt(i));
if(alpha1[from_a1] != alpha2[from_a2]) return false;
alpha1[from_a1] = i + 1;
alpha2[from_a2] = i + 1;
}
return true;
}
}
Jan 10 - Isomorphic Strings; String; Data Type: char; digit and letter
标签:
原文地址:http://www.cnblogs.com/5683yue/p/5120081.html