1、题目
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.
please:
2、代码实现
public class Solution {
public static char findTheDifference(String s, String t) {
if (s == null || t.length() == 0)
return t.charAt(0);
if (t == null || t.length() == 0)
return s.charAt(0);
if (s == null && t == null)
return 0;
int[] a = new int[30];
char[] tChars = t.toCharArray();
char[] sChars = s.toCharArray();
int sLength = s.length();
int tLength = t.length();
if (sLength > tLength) {
for (int i = 0; i < sChars.length; i++) {
if (a[sChars[i] - 97] != 0)
a[sChars[i] - 97] = ++(a[sChars[i] - 97]);
else
a[sChars[i] - 97] = 2;
}
for (int i = 0; i < tChars.length; i++) {
a[tChars[i] - 97] = --(a[tChars[i] - 97]);
}
} else {
for (int i = 0; i < tChars.length; i++) {
if (a[tChars[i] - 97] != 0)
a[tChars[i] - 97] = ++(a[tChars[i] - 97]);
else
a[tChars[i] - 97] = 2;
}
for (int i = 0; i < sChars.length; i++) {
a[sChars[i] - 97] = --(a[sChars[i] - 97]);
}
}
for (int i = 0; i < 30; i ++) {
if (a[i] >= 2) {
return (char) (i + 97);
}
}
return 0;
}
}