389. Find the Difference

原创 2016年08月29日 08:09:47

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.
Subscribe to see which companies asked this question

解题思路:就是用个hashmap存储字母分布,然后找出不一样的。这里直接用Java的hashmap,因为题目限定是小写字母,其实可以使用26位的数组即可。

public class Solution {
    public char findTheDifference(String s, String t) {
        int slen = s.length();
        int tlen = t.length();
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        for(int i = 0; i < slen; i++)
        {
            if(map.containsKey(s.charAt(i)))
            {
                int value = map.get(s.charAt(i));
                value++;
                map.put(s.charAt(i), value);
            }else{
                map.put(s.charAt(i), 1);
            }
        }
        char res='\0';
        for(int i = 0; i < tlen; i++)
        {
            if(map.containsKey(t.charAt(i)))
            {
              int value = map.get(t.charAt(i));
              value--;
              if(value < 0)
              {
                  res = t.charAt(i);
                  break;
              }
              map.put(t.charAt(i), value);
            }else{
                res = t.charAt(i);
                break;
            }

        }
        return res;
    }
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

389. Find the Difference

原题链接: https://leetcode.com/problems/find-the-difference/ 题目: Given two strings s and t which cons...

LeetCode笔记:389. Find the Difference

在两个字符串中找出唯一多出的那个字母

LeetCode 389. Find the Difference

题意两个字符串s,t,都是小写字母,t由s中的字符和新增的一个字母随机排列组合而成,找出新增的字符!思路最直接的思路是HashMap,根据字符串s建立一个HashMap,key是字母,value是字母...

leetcode389. Find the Difference

389. Find the DifferenceGiven two strings s and t which consist of only lowercase letters.String t i...

leetcode算法——389. Find the Difference(基于JAVA)

Given two strings s and t which consist of only lowercase letters. String t is generated by random s...

389. Find the Difference [easy] (Python)

题目链接https://leetcode.com/problems/find-the-difference/题目原文 Given two strings s and t which consist...

【LeetCode】389 Find the Difference(java)

原题Given two strings s and t which consist of only lowercase letters.String t is generated by random ...

Tutorial: 389. Find the Difference

LeetCode算法题:389. Find the Difference的解法。

[LeetCode]389. Find the Difference(找不同)

389. Find the DifferenceGiven two strings s and t which consist of only lowercase letters. String t...

389. Find the Difference

389. Find the Difference1 题目Given two strings s and t which consist of only lowercase letters.String...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)