​LeetCode刷题实战389:找不同

程序IT圈

共 1627字,需浏览 4分钟

 ·

2021-09-27 07:20

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 找不同,我们先来看题面:
https://leetcode-cn.com/problems/find-the-difference/

You are given two strings s and t.

String t is generated by random shuffling string s and then add one more letter at a random position.

Return the letter that was added to t.

给定两个字符串 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"


解题

主要思路:

将两个字符串按照字母序进行排序,然后从头开始遍历,找出第一个不相等的元素即为所求。

class Solution {
public:
    char findTheDifference(string s, string t) {
        sort(s.begin(),s.end());
        sort(t.begin(),t.end());
        int i=0;
        while(s[i]==t[i]){
            i++;
        }
        return t[i];
    }
};


好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-380题汇总,希望对你有点帮助!

LeetCode刷题实战381:O(1) 时间插入、删除和获取随机元素

LeetCode刷题实战382:链表随机节点

LeetCode刷题实战383:赎金信

LeetCode刷题实战384:打乱数组

LeetCode刷题实战385:迷你语法分析器

LeetCode刷题实战386:字典序排数
LeetCode刷题实战387:字符串中的第一个唯一字符
LeetCode刷题实战388:文件的最长绝对路径

浏览 12
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报