LC1472.双胞胎字符串

本文详细解析了LC1472题目的解决方案,通过对比两个字符串的奇数位和偶数位,判断是否可以通过交换达到目标字符串。提供了Python和C++两种实现方式,并解释了关键算法步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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。

### 关于字符串 LeetCode 算法题解决方案 解决字符串相关的 LeetCode 题目通常涉及多种技巧,包括但不限于双指针、滑动窗口、哈希表以及动态规划等方法。以下是几个常见的字符串处理问题及其可能的解法。 #### 1. 双指针技术 对于一些需要比较两个字符串或者在一个字符串中寻找特定子串的问题,可以采用双指针技术来优化时间复杂度。例如,在判断回文字符串时,可以通过设置头尾两个指针逐步向中间移动并对比字符是否相等[^1]。 ```python def is_palindrome(s: str) -> bool: left, right = 0, len(s) - 1 while left < right: if not s[left].isalnum(): left += 1 continue if not s[right].isalnum(): right -= 1 continue if s[left].lower() != s[right].lower(): return False left += 1 right -= 1 return True ``` #### 2. 滑动窗口算法 当题目涉及到连续子数组或子字符串的最大最小长度等问题时,滑动窗口是一种非常有效的策略。比如求解最长无重复字符子串问题就可以利用此方法实现O(n)的时间效率[^2]。 ```python def length_of_longest_substring(s: str) -> int: char_index_map = {} max_length = start = 0 for i, c in enumerate(s): if c in char_index_map and start <= char_index_map[c]: start = char_index_map[c] + 1 else: max_length = max(max_length, i - start + 1) char_index_map[c] = i return max_length ``` #### 3. 哈希表应用 许多关于查找某个模式是否存在或者统计频率类别的题目都可以借助哈希结构快速完成操作。像字母异位词分组这样的挑战就非常适合通过构建字典来进行分类存储[^3]。 ```python from collections import defaultdict def group_anagrams(strs: list[str]) -> list[list[str]]: anagram_dict = defaultdict(list) for string in strs: key = ''.join(sorted(string)) anagram_dict[key].append(string) return list(anagram_dict.values()) ``` #### 4. 动态规划思路 某些复杂的辑距离计算或者是序列匹配类型的习题则需要用到动态规划的思想去分解成更小规模的状态转移方程解答[^4]。 ```python def min_distance(word1: str, word2: str) -> int: m, n = len(word1), len(word2) dp = [[0]*(n+1) for _ in range(m+1)] for i in range(1,m+1): dp[i][0]=i for j in range(1,n+1): dp[0][j]=j for i in range(1,m+1): for j in range(1,n+1): if word1[i-1]==word2[j-1]: cost=0 else:cost=1 dp[i][j]=min(dp[i-1][j]+1, dp[i][j-1]+1, dp[i-1][j-1]+cost) return dp[m][n] ``` 以上仅列举了几种典型场景下的程实践案例供参考习之用。每道具体的LeetCode题目都有其独特的背景设定和边界条件考量因素,因此实际码过程中还需要仔细审阅题目描述,并充分测试各种极端情况下的表现效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值