LeetCode 389 找不同 HERODING的LeetCode之路

给定两个字符串 s 和 t,它们只包含小写字母。

字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。

请找出在 t 中被添加的字母。

示例 1:

输入:s = “abcd”, t = “abcde”
输出:“e”
解释:‘e’ 是那个被添加的字母。

示例 2:

输入:s = “”, t = “y”
输出:“y”

示例 3:

输入:s = “a”, t = “aa”
输出:“a”

示例 4:

输入:s = “ae”, t = “aea”
输出:“a”

提示:

0 <= s.length <= 1000
t.length == s.length + 1
s 和 t 只包含小写字母

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-the-difference
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路:
众所周知c++对字符串操作相当不友好,一开始我还在想用map存储字母,但是删除不好删除,vector也可以解决,但是要排序,这里直接暴力加减,最后的结果返回ASCII!一开始我还在想返回int是不是写错了,仔细思考才发现精妙,代码如下:

class Solution {
    
    
public:
    char findTheDifference(string s, string t) {
    
    
        int sum = 0;
        for(auto i : t){
    
    
            sum += i;
        }
        for(auto i : s){
    
    
            sum -= i;
        }
        return sum;
    }
};


/*作者:heroding
链接:https://leetcode-cn.com/problems/find-the-difference/solution/yi-xiang-bu-dao-de-si-lu-by-heroding-npqk/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/

排序的方法如下:

class Solution {
    
    
public:
    char findTheDifference(string s, string t) {
    
    
        sort(s.begin(), s.end());
        sort(t.begin(), t.end());
        for(int i = 0; i < s.length(); i ++){
    
    
            if(s[i] != t[i]){
    
    
                return char(t[i]);
            }
            continue;
        }
        return char(t[s.length()]);
    }
};

/*作者:heroding
链接:https://leetcode-cn.com/problems/find-the-difference/solution/yi-xiang-bu-dao-de-si-lu-by-heroding-npqk/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/

猜你喜欢

转载自blog.csdn.net/HERODING23/article/details/111350739
今日推荐