Find the Difference —— leetcode

来源:互联网 发布:淘宝代销经营地址 编辑:程序博客网 时间:2024/06/05 18:30

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:eExplanation:'e' is the letter that was added.

本题较为简单。我的算法是将第一个字符串中的每个字符存入数组m中,即m[char]++,再通过第二个字符串寻找多出的字符,即m[char]--,当找到一个字符c的m[c]<0,则c为多出的字符,该算法的复杂度是O(n)。

程序代码如下所示:

</pre><pre name="code" class="cpp">class Solution {public:    char findTheDifference(string s, string t) {        int m[26];                memset(m,0,sizeof(m));                for(int i=0;i<s.size();++i){            m[s[i] - 'a']++;        }                 for(int i=0;i<t.size();++i){            m[t[i] - 'a']--;            if(m[t[i] - 'a'] < 0) return t[i];        }    }};



0 0