Given two strings s and t which consist of only lowercase letters.git
String t is generated by random shuffling string s and then add one more letter at a random position.github
Find the letter that was added in t.數組
Example:dom
Input: s = "abcd" t = "abcde" Output: e Explanation: '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-xincode