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.
题目叫 "找出不同点",题目本身也比较简单。有两个字符串 s 和 t,它们只包含小写的字母。字符串 t 是由字符串 s 产生的,只比 s 多一个字母。题目的目的就是要找出这个多出的字母。
解法一:这种解法比较直接,建立以个 map 对应字符串 s,key 为字符,value 就是该字符出现的次数。首先遍历字符串 s,来建立这个 map,然后再遍历字符串 t。对 t 中出现的每个字符,都从 map 中减一,当 value 值小于 0 时,则说明该字符就是多出的字符。代码我就不列出来了,这种解法和第二种类似,大家看了第二种解法就明白了。
解法二:第一种解法的 map 有点太重了,而且涉及到 Character 和 char,int 和 Integer 之间的转换,我也不喜欢。所以,我就用了另一种很类似的方法——int 数组来代替 map。因为字符串只有小写字母,也就是只有 26 中可能,那么建立一个 int[16] 的数组即可,索引就是字符 char-'a',而数组值就是字符出现在字符串 s 中的次数。说白了,和解法二思路一致。代码如下:
- public char findTheDifference(String s, String t) {
- int[] nums = new int[26];
- for (int i = 0; i < s.length(); i++) {
- char ch = s.charAt(i); ++nums[ch - 'a'];
- }
- char ret = 'a';
- for (int i = 0; i < t.length(); i++) {
- char ch = t.charAt(i); --nums[ch - 'a'];
- if (nums[ch - 'a'] < 0) {
- ret = ch;
- break;
- }
- }
- return ret;
- }
解法三:由于字符串 t 只比字符串 s 多了一个字符,那么直接用 t 中所有字符值的和减去字符串 s 中字符值的和即可。
- public char findTheDifference(String s, String t) {
- int ret = 0;
- for (int i = 0; i < s.length(); i++) {
- ret -= (int) s.charAt(i);
- }
- for (int i = 0; i < t.length(); i++) {
- ret += (int) t.charAt(i);
- }
- return (char) ret;
- }
解法四:另外一种思路,既然字符串 t 只比字符串 s 多了一个字符,也就是说大部分字符都是相同的。那么,我们可以使用异或的方式,来找出这个不同的值。
- public char findTheDifference(String s, String t) {
- int ret = 0;
- for (int i = 0; i < s.length(); i++) {
- ret ^= s.charAt(i);
- }
- for (int i = 0; i < t.length(); i++) {
- ret ^= t.charAt(i);
- }
- return (char) ret;
- }
来源: http://www.cnblogs.com/styshoo/p/5922397.html