给定两个字符串s和t,判断它们是否是同构的。如果字符串s可以通过字符替换的方式得到字符串t,则称s和t是同构的。字符的每一次出现都必须被其对应字符所替换,同时还需要保证原始顺序不发生改变。两个字符不能映射到同一个字符,但是字符可以映射到其本身。
相同的题目:
对于仅由小写字母组成的字符串A和字符串B,如果分别存在一个小写字母由a到z的排列,使得将A中所有字母a替换为排列的第一个字母,所有字母B替换为第二个字母,所有字母z替换为排列的最后一个字母之后,A和B完全相同。那么称字符串A和字符串B相似,如abcc和xyaa。现在给定长度不超过10**5的字符串S和T,求S中有多少子串与T相似?
public class Main {
static int solve(String S, String T) {
int lenS = S.length();
int lenT = T.length();
int count = 0;
if (lenS < lenT) {
for (int i = 0; i <= lenT - lenS; i++) {
if (isIsomorphic((String) T.subSequence(i, i + lenS), S)) {
count++;
}
}
} else {
for (int i = 0; i <= lenS - lenT; i++) {
if (isIsomorphic((String) S.subSequence(i, i + lenT), T)) {
count++;
}
}
}
return count;
}
public static boolean isIsomorphic(String s, String t) {
if (s == null || t == null) {
return false;
}
HashMap<Character, Character> hashMap = new HashMap<Character, Character>();
for (int i = 0; i < s.length(); i++) {
char c1 = s.charAt(i);
char c2 = t.charAt(i);
if (hashMap.containsKey(c1)) {
if (hashMap.get(c1) == c2) {
continue;
} else {
return false;
}
} else {
if (hashMap.containsValue(c2)) {
return false;
} else {
hashMap.put(c1, c2);
}
}
}
return true;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int res;
String _S;
try {
_S = in.nextLine();
} catch (Exception e) {
_S = null;
}
String _T;
try {
_T = in.nextLine();
} catch (Exception e) {
_T = null;
}
res = solve(_S, _T);
System.out.println(String.valueOf(res));
}
}