Skip to content

Latest commit

 

History

History
37 lines (32 loc) · 1 KB

Find_the_Difference.md

File metadata and controls

37 lines (32 loc) · 1 KB

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.

Code:


class Solution {
    public char findTheDifference(String s, String t) {
        int[] letters = new int[26];
        for (char c : s.toCharArray()) letters[c - 'a']++;
        for (char c : t.toCharArray()) {
            if (--letters[c - 'a'] < 0) return c;
        }
        return 0;
    }
}

  • 常规的字符串类型的题目,使用数组作为字符表,存入出现次数;
  • 对于字符串s,出现元素则++,对于字符串t,出现元素则--;
  • 由于初始化字符串全零,所以当次数小于零时,则返回当前字符;
  • 字符类型的返回值,空的情况可以返回0。