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.
class Solution {
    public char findTheDifference(String s, String t) {
        List<Character> list = new ArrayList();
        for(char c: t.toCharArray()){
            list.add(c);
        }
        for(char c: s.toCharArray()){
            if(list.indexOf(c) >= 0){
                list.remove(list.indexOf(c));
            }
        }
        return list.get(0);
    }
}

我怎么老把遍历对象搞错卧槽?

想法是:把t存起来,然后遍历s,发现当前char在t中就remove,最后剩下的就是答案

class Solution {
    public char findTheDifference(String s, String t) {
        int ss = 0;
        int tt = 0;
        for(char c: s.toCharArray()) ss += (int) c;
        for(char c: t.toCharArray()) tt += (int) c;
        return (char) (tt - ss);
    }
}

刚还在那想能不能两个一减,卧槽真能

posted @ 2020-05-11 11:42  Schwifty  阅读(159)  评论(0编辑  收藏  举报