389. Find the Difference

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.

本题开始的时候以为是顺序没有被打乱,导致出现错误。后来想出了一个用hashmap来存储字符-出现次数对,将s里面的字符存进去,然后去寻找t,如果t里面存在,将出现的次数-1,如果不存在,
则这个字符就是我们要找的,代码如下:
 1 public class Solution {
 2     char ch;
 3     public char findTheDifference(String s, String t) {
 4         Map<Character,Integer> map = new HashMap<>();
 5         for(char c:s.toCharArray()){
 6             map.put(c,map.getOrDefault(c,0)+1);
 7         }
 8         for(char c:t.toCharArray()){
 9             if(map.containsKey(c)){
10                 if(map.get(c)>1) map.put(c,map.get(c)-1);
11                 else map.remove(c);
12             }else{
13                 ch = c;
14             }
15         }
16         return ch;
17     }
18 }

第二种方法是使用数组来存储字符出现个数,道理和第一题一样,代码如下:

 1 public class Solution {
 2     public char findTheDifference(String s, String t) {
 3         char c = 'a';
 4         int[] word=  new int[26];
 5         for(int i=0;i<s.length();i++){
 6             word[s.charAt(i)-'a']++;
 7         }
 8         for(int i=0;i<t.length();i++){
 9             if(word[t.charAt(i)-'a']--<=0){
10                 c = t.charAt(i);
11                 break;
12             }
13         }
14         return c;
15     }
16 }

 第三种方法就是以前做过的那个方法,用异或来解决,代码如下:

 1 public class Solution {
 2     public char findTheDifference(String s, String t) {
 3         char c = t.charAt(t.length()-1);
 4         for(int i=0;i<s.length();i++){
 5             c^=s.charAt(i);
 6             c^=t.charAt(i);
 7         }
 8         return c;
 9     }
10 }

 

posted @ 2017-03-23 01:09  CodesKiller  阅读(217)  评论(0编辑  收藏  举报