LC1472.雙胞胎字符串
給定兩個字符串 s和t,每次可以任意交換s的奇數位或偶數位上的字符,即奇數位上的字符能與其他奇數位的字符互換,而偶數位上的字符能與其他偶數位的字符互換,問能否經過若干次交換,使s變成t。
第一版提交:
Python3
class Solution:
"""
@param s: the first string
@param t: the second string
@return: If they are twin strings
"""
def isTwin(self, s, t):
# Write your code here
so = []
to = []
se = []
te = []
for i in range(0, len(s), 2):
so.append(s[i])
to.append(t[i])
for j in range(1, len(s), 2):
se.append(s[j])
te.append(t[j])
so.sort()
to.sort()
se.sort()
te.sort()
if so == to and se == te:
return "Yes"
return "No"
思路很直接,s和t的奇數位和偶數位分別比較,Python3中亂序的兩相同元素的列表並不能相等,需排序後比較。
九章算法中利用hashmap
C++
class Solution {
public:
/**
* @param s: the first string
* @param t: the second string
* @return: If they are twin strings
*/
int a[127], b[127];
string isTwin(string &s, string &t) {
// Write your code here
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
for (int i = 0; i < s.length(); i++) {
if (i & 1) {
a[s[i]]++;
a[t[i]]--;
} else {
b[s[i]]++;
b[t[i]]--;
}
}
for (int i = 0; i < 127; i++) {
if (a[i] != 0 || b[i] != 0) return "No";
}
return "Yes";
}
};
回顧一下memset:
memset(void *s, int ch, size_t n)
函數說明:將s所指向的某一塊內存中的前n個字節的內容全部設置爲ch指定的ASCLL值,其返回值爲指向s的指針。
ASCLL表:標準ASCLL碼128種字符,擴展ASCLL碼256,字母數字等在標準ASCLL碼中。這裏要說明ASCLL 中0代表空字符,127代表DELETE。