2019独角兽企业重金招聘Python工程师标准>>>
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: eExplanation: 'e' is the letter that was added.
//既然都是小写字母 那么用之前的数组也是解决的 //这种方法与使用map是相同的 public static char findTheDifference(String s, String t) {int[] arr = new int[26];for (int i = 0; i < t.length(); i++) {arr[t.charAt(i) - 'a']++;}for (int i = 0; i < s.length(); i++) {--arr[s.charAt(i)-'a'];}for (int i =0;i< arr.length;i++){if(arr[i]>0){return (char)(i+'a');}}return ' '; }
//原来还可以这么写呀 public static char findTheDifference2(String s, String t) {char c = 0;for (int i = 0; i < s.length(); ++i) {c ^= s.charAt(i);}for (int i = 0; i < t.length(); ++i) {c ^= t.charAt(i);}return c; }
//写的看上去简略一点 少循环一次 public static char findTheDifference3(String s, String t) {int n = t.length();char c = t.charAt(n - 1);for (int i = 0; i < n - 1; ++i) {c ^= s.charAt(i);c ^= t.charAt(i);}return c; }
git:https://github.com/woshiyexinjie/leetcode-xin