[LeetCode]389. Find the Difference(找不同)

389. Find the Difference

Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
题目大意:
给定两个只由小写字母组成的字符串s和t。
字符串t由字符串s 随机洗牌(打乱顺序) 生成,然后在随机位置添加一个字母。
找到在t中添加的字母。
Example:

Input:
s = "abcd"
t = "abcde"

Output:
e

Explanation:
'e' is the letter that was added.

思路:遍历两个字符串,将t中与s相同的字符统统赋值为’0’,剩下的一个未被赋值的字符即为要找的字母

代码如下:

C++

#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
    char findTheDifference(string s, string t) {
        int s_length = s.length();
        int t_length = t.length();
        for(int i=0;i<s_length;i++)//遍历字符串s
        {
            for(int j=0;j<t_length;j++)//遍历字符串t
            {
                if(s[i] == t[j])//若在字符串t中 找到与 字符串s中元素 相同的字符
                {
                    t[j] = '0';//将t中该元素赋值'0'
                    break;//并结束遍历字符串t
                }
            }

        }
        for(int m=0;m<t_length;m++)//遍历字符串t
        {
            if(t[m] != '0')//找到没有被赋值为'0'的元素 返回该值
                return t[m];
        }
        return t[s_length];
    }
};
int main()
{
    Solution a;
    cout << a.findTheDifference("aa", "aea") << endl;
    return 0;
}

注意:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值