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.dom
Find the letter that was added in t.code
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时,则说明该字符就是多出的字符。代码我就不列出来了,这种解法和第二种相似,你们看了第二种解法就明白了。string
解法二:第一种解法的map有点过重了,并且涉及到Character和char,int和Integer之间的转换,我也不喜欢。因此,我就用了另外一种很相似的方法——int数组来代替map。由于字符串只有小写字母,也就是只有26种可能,那么创建一个int[26]的数组便可,索引就是字符char-'a',而数组值就是字符出如今字符串s中的次数。说白了,和解法二思路一致。代码以下:it
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中字符值的和便可。io
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; }