leetcode [#389]

目录

题目

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.


解决方案

1
2
3
4
5
6
7
8
9
10
public class Solution {
public char findTheDifference(String s, String t) {
if ((s.length() == 0)) return t.charAt(0);
char result = 'a';
List<Character> list = new ArrayList<>();
for(int i = 0; i < t.length(); i++) list.add(t.charAt(i));
for(int j = 0; j < s.length(); j++) list.remove((Character) s.charAt(j));
return list.get(0);
}
}

注意事项

  1. 将t的每个字符加入arraylist。
  2. 遍历s,将s的每个字符从list中取出,剩下的就是新增的。