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:
Input:
 
s = "a"
t = "aa"
 
Output:
a
 


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;
    }
}

 


3、总结

看到2个字符串对比,我么可以先转化为字符数组,下表从A - 65 活着  a - 95  开始,也就是从下表0开始,然后要注意2个字符串里面可能包含同样的元素有几个的情况,相同就往上加,另外一个就减,但是他们最多相差1个字符,所以,我们可可以肯定,比我们一开始设置的大,也就是3,然后如果没有重复的数据,那么一样的就为1,肯定有一个为2.