389. 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.

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

[一句话思路]:

用26数组,先加后减

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

有两种方法取出字母:.toCharArray(无参) 字符串.charAt()。

异或是个好东西。

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[关键模板化代码]:

//for loop, +t, -s 
        for (int i = 0; i < t.length(); i++) {
            alpha[t.charAt(i) - 'a']++;
        }

[其他解法]:

异或运算符是用符号“^”表示的,其运算规律是:
两个操作数的位中,相同则结果为0,不同则结果为1。

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

class Solution {
    public char findTheDifference(String s, String t) {
        //ini char[]
        int[] alpha = new int[26];
        
        //for loop, +t, -s 
        for (int i = 0; i < t.length(); i++) {
            alpha[t.charAt(i) - 'a']++;
        }
        
        for (int i = 0; i < s.length(); i++) {
            alpha[s.charAt(i) - 'a']--;
        }
        
        //return res
        for (int j = 0; j < 26; j++) {
            if (alpha[t.charAt(j) - 'a'] != 0) {
                return t.charAt(j);
            }
        }
        
        return 0;
    }
}
View Code

 

posted @ 2018-04-24 16:08  苗妙苗  阅读(210)  评论(0编辑  收藏  举报