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。