前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
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中每个字符出现的次数。 Your runtime beats 27.71% of java submissions.
public class Solution {
public char findTheDifference(String s, String t) {
int[] alphabet = new int[26];
for(int i = 0; i < s.length(); i ++) alphabet[s.charAt(i) - 'a'] ++;
char result = 'a';
for(int i = 0; i < t.length(); i ++) {
alphabet[t.charAt(i) - 'a'] --;
if(alphabet[t.charAt(i) - 'a'] < 0){
result = t.charAt(i);
break;
}
}
return result;
}
}