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.
思路:
(1)题意为给定字符串s和字符串t,其中字符串t是在字符串s的任意位置增加一个字符构成的字符串,要求对比两个字符串找出这个字符。
(2)该题比较简单。下面简单介绍几种解题思路:
a、一种方法可以将两字符串转换为两个字符数组并排序,然后设定两个指针分别对数组中相同位置的字符进行对比,如果发现不同,则从字符串s中当前比较的字符即为所求。
b、另一种方法可以用map将字符串t中的所有字符和字符对应的个数存储,然后遍历字符串s,如果从字符串s中取出的字符存在于map中,则将map中该字符对应的数值减1;如果不存在;则当前遍历的字符即为所求。
c、还有一种方法是通过位运算,由于字符串s和字符串t中仅有一个字符不一样,那么将这两个字串中的所有字符按位异或(^),那么最后剩下的字符即为所求。还有其它很多方法这里就不列举了。
(3)算法代码实现如下所示。希望对你有所帮助。
//解法 1
public class Solution {
public char findTheDifference(String s, String t) {
if (s == null || t == null)
return ' ';
char[] c1 = s.toCharArray();
char[] c2 = t.toCharArray();
Arrays.sort(c1);
Arrays.sort(c2);
int len = c1.length > c2.length ? c2.length : c1.length;
for (int i = 0; i < len; i++) {
if (c1[i] == c2[i]) {
continue;
} else {
if (c1.length > c2.length) {
return c1[i];
} else {
return c2[i];
}
}
}
return c1.length > c2.length ? c1[c1.length - 1] : c2[c2.length - 1];
}
}
//解法2
public class Solution {
public char findTheDifference(String s, String t) {
if (s == null || t == null || t.length()==0)
return ' ';
if(s.length()==0 && t.length()!=0)
return t.charAt(0);
char c = s.charAt(0);
for(int i = 1; i<s.length();i++) {
c^=s.charAt(i);
}
for(char n : t.toCharArray()){
c^=n;
}
return c;
}
}