Find the Difference (E)
題目
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.
題意
字串t由字串s亂序后加入一個隨機字母得到,求這個隨機的字母,
思路
直接hash記錄每個字符的個數在進行比較,
代碼實作
Java
class Solution {
public char findTheDifference(String s, String t) {
int[] hash = new int[26];
for (char c : s.toCharArray()) {
hash[c - 'a']++;
}
for (char c : t.toCharArray()) {
hash[c - 'a']--;
}
int i = 0;
while (hash[i] == 0) {
i++;
}
return (char)('a' + i);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/121941.html
標籤:其他
