MDGSF Software Engineer

[算法学习][leetcode] 389 Find the Difference

2017-09-02
mdgsf
Art

https://leetcode.com/problems/find-the-difference/description/

题目

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.

Example:

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

Output:
e

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

题目翻译

题目解析

参考答案

#include <iostream>
using namespace std;

class Solution {
public:
    char findTheDifference(string s, string t) {

        int aiANSI[128] = { 0 };
        for (char c : s)
        {
            aiANSI[c]++;
        }

        for (char c : t)
        {
            aiANSI[c]--;
        }

        for (int i = 0; i < 128; i++)
        {
            if (aiANSI[i] != 0)
            {
                return (char)i;
            }
        }
        return 0;
    }
};

int main()
{
    Solution o;
    cout << o.findTheDifference("abcd", "abcde") << endl;
    return 0;
}

weixingongzhonghao

Similar Posts

Comments