Easy
559244FavoriteShare
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.
C++:
/*
* @Autor: SourDumplings
* @Date: 2019-09-20 08:35:52
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/find-the-difference/
*/
class Solution
{
public:
char findTheDifference(string s, string t)
{
int hashTable[26];
fill(hashTable, hashTable + 26, 0);
for (auto &&c : s)
{
++hashTable[c - 'a'];
}
for (auto &&c : t)
{
int i = c - 'a';
if (hashTable[i] == 0)
{
return c;
}
else
{
--hashTable[i];
}
}
return -1;
}
};
Java:
import java.util.Arrays;
/*
* @Autor: SourDumplings
* @Date: 2019-09-20 08:45:12
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/find-the-difference/
*/
class Solution
{
public char findTheDifference(String s, String t)
{
int[] hashTable = new int[26];
int ls = s.length();
int lt = t.length();
Arrays.fill(hashTable, 0);
for (int i = 0; i < ls; i++)
{
char c = s.charAt(i);
++hashTable[c - 'a'];
}
for (int i = 0; i < lt; i++)
{
char c = t.charAt(i);
int j = c - 'a';
if (hashTable[j] == 0)
{
return c;
}
else
{
--hashTable[j];
}
}
return ' ';
}
}