LC1472.双胞胎字符串

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。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值