LeetCode.389 Find the Difference

来源:互联网 发布:国内贸易用什么软件 编辑:程序博客网 时间:2024/05/18 14:25
题目:

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:eExplanation:'e' is the letter that was added.
分析(推荐):
class Solution {    public char findTheDifference(String s, String t) {        //给定两个字符串s和t,t是由字符串s和另外一个字母随机打乱组成的,返回该随机字母        //思路:使用一个字母数组来记录匹配串中的个数,最后通过匹配查找串,剩下来的就是多出来的那个字母        int [] alpha=new int[26];        for(char c:s.toCharArray()){            alpha[c-'a']++;        }        for(char c:t.toCharArray()){            alpha[c-'a']--;        }                //查找多出来的那个        for(int i=0;i<26;i++){            if(alpha[i]!=0){                return (char)('a'+i);            }        }        return ' ';    }}

分析2(原创-易理解):
class Solution {    public char findTheDifference(String s, String t) {        //给定两个字符串s和t,t是由字符串s和另外一个字母随机打乱组成的,返回该随机字母        //思路:使用HashMap实现,直接匹配参考值        //注意:需要考虑随机字母可能与其他字母存在相同的情况        HashMap<Character,Integer> hm=new HashMap<Character,Integer>();        char c=' ';        for(int i=0;i<s.length();i++){            hm.put(s.charAt(i),hm.getOrDefault(s.charAt(i),0)+1);        }                for(int i=0;i<t.length();i++){            if(hm.containsKey(t.charAt(i))&&hm.get(t.charAt(i))>0){                //匹配到相同的,就减去1,以防随机字母与其他字母相同                hm.put(t.charAt(i),hm.get(t.charAt(i))-1);            }else {                c=t.charAt(i);                return c;                }        }        return c;    }}


原创粉丝点击