leetcode389.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.
假設兩個只包含小寫字母的字串s和t,其中t是s中字母的亂序,並在某個位置上添加了一個新的字母。問新增的這個新的字母是什麼?
思路一:字元陣列
我們可以利用一個整數陣列來記錄所有字元出現的次數,在s中出現一次相應計數加一,在t中出現一次則減一。最後只需要遍歷整數陣列檢查是否有某個字元計數大於0。則該字元就是多餘的字元。
public char findTheDifference(String s, String t) { int[] count = new int[26]; for(int i = 0 ; i<t.length() ; i++) { if(i != t.length()-1) { count[s.charAt(i)-'a']++; } count[t.charAt(i)-'a']--; } for(int i = 0 ; i<count.length ; i++) { if(count[i] != 0) { return (char)('a' + i); } } return 'a'; }
思路二:求和
我們知道,字元對應的ascii碼是唯一的,那麼既然兩個字串相比只有一個多餘的字元,那麼二者的ascii碼和相減就可以找到唯一的字元的ascii碼。
public char findTheDifference2(String s, String t){ int value = 0; for(int i = 0 ; i<s.length() ; i++) { value -= s.charAt(i); value += t.charAt(i); } char result = (char)(value + t.charAt(t.length()-1)); return result; }