思路
新建四個數組
mapA,mapB
用來放置字符串中的元素,
arrA,arrB
用來記錄字符串在map中對應的位置
兩次循環分別遍歷兩個字符串,并進行放置元素到map數組的操作和在arr中記錄位置,完事后判斷arrA和arrB是不是相等,如果相等,則返回true
測試示例
代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>205. Isomorphic Strings</title>
</head>
<body>
<p>
Given two strings s and t, determine if they are isomorphic.
<br/>
Two strings are isomorphic if the characters in s can be replaced to get t.
<br/>
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.
<br/>
For example,
Given "egg", "add", return true.
<br/>
Given "foo", "bar", return false.
<br/>
Given "paper", "title", return true.
<br/>
Note:
You may assume both s and t have the same length.
<br/>
Subscribe to see which companies asked this question.
</p>
<p>
給定兩個字符串s和t,判斷它們是否是同構的。
<br/>
如果字符串s可以通過字符替換的方式得到字符串t,則稱s和t是同構的。
<br/>
字符的每一次出現都必須被其對應字符所替換,同時還需要保證原始順序不發生改變。兩個字符不能映射到同一個字符,但是字符可以映射到其本身。
<br/>
測試樣例如題目描述。
<br/>
可以假設s和t等長。
</p>
<script>
/**
* 是否是同構
* @param s
* @param t
* @return {boolean}
*/
function isIsomorphic(s, t) {
if (s.length !== t.length) {
return false;
}
var mapA = [], mapB = []; // 用來放字符串的每個字母
var arrA = [], arrB = []; // 用來記錄字符串的每個字母在map數組中的位置
var i;
for (i = 0; i < s.length; i++) {
if (mapA.indexOf(s[i]) === -1) {
mapA.push(s[i]);
}
arrA[i] = mapA.indexOf(s[i]);
}
for (i = 0; i < t.length; i++) {
if (mapB.indexOf(t[i]) === -1) {
mapB.push(t[i]);
}
arrB[i] = mapB.indexOf(t[i]);
}
console.log('mapA = ' + JSON.stringify(mapA));
console.log('arrA = ' + JSON.stringify(arrA));
console.log('mapB = ' + JSON.stringify(mapB));
console.log('arrB = ' + JSON.stringify(arrB));
/**
* 判斷數組是否相等(簡單數組)
* @param arrA
* @param arrB
*/
function isArrayEqual(arrA, arrB) {
return JSON.stringify(arrA) === JSON.stringify(arrB);
}
// 判斷arrA和arrB是否相等
return isArrayEqual(arrA, arrB);
}
var a = 'egg';
var b = 'add';
console.log(isIsomorphic(a, b));
</script>
</body>
</html>