字符串找不同

每日一题(12.18)

389简单:给定两个字符串 s 和 t,它们只包含小写字母。字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。请找出在 t 中被添加的字母。
示例: s=“abcd”; t=“abcde” “e”
链接:https://leetcode-cn.com/problems/find-the-difference

思路:
审题都是小写字母,且只有一个字母的差异,因此考虑转换成数值,求差,再反转
转ASCII码值ord()
转字母chr()

class Solution:
    def findTheDifference(self, s: str, t: str) 
### C++ 中比较两个字符串不同之处的方法 当涉及到出两个字符串之间的差异时,可以采用多种方法来实现这一目标。对于 `std::string` 对象而言,可以直接遍历字符并逐个对比;而对于C风格字符串,则需借助特定函数。 #### 使用 `std::string` 通过迭代器访问每个字符,并逐一比较两串中的对应位置字符: ```cpp #include <iostream> #include <string> void findDifferences(const std::string& str1, const std::string& str2) { size_t minLength = std::min(str1.length(), str2.length()); for (size_t i = 0; i < minLength; ++i) { if (str1[i] != str2[i]) { std::cout << "Difference at position " << i << ": '" << str1[i] << "' vs '" << str2[i] << "'" << std::endl; } } // 输出剩余部分作为区别 if (str1.length() > minLength || str2.length() > minLength) { std::cout << "One string is longer than the other." << std::endl; } } ``` 这段代码会打印出第一个不匹配的位置及其对应的字符[^1]。 #### 处理C风格字符串 针对C风格字符串(即以null终止符结尾的字符数组),可利用标准库提供的 `strncmp()` 函数来进行长度受限的比较操作,或者手动编写循环逻辑完成相似功能: ```cpp #include <cstring> // For strlen and strncmp functions void cStringDiff(const char* s1, const char* s2) { size_t lengthLimit = std::strlen(s1); int result; while ((result = strncmp(s1++, s2++, 1)) == 0 && *s1 != '\0' && *s2 != '\0') {} if (*s1 == '\0' && *s2 == '\0') return; // Strings are equal up to their lengths printf("First difference found after comparing %zu characters.\n", lengthLimit - std::strlen(s1)); if(result != 0){ printf("Different character codes: %d vs %d\n", static_cast<int>(*s1), static_cast<int>(*s2)); }else{ printf("Strings differ only by length."); } } ``` 此段程序不仅指出了首次发现不同的地方,还报告了具体字符编码上的差别以及可能存在的仅因长度而异的情况[^2]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值