LeetCode - 389. Find the Difference
2017-09-07 21:09
393 查看
Q:
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:
A:
主要思路:
先for遍历字符串s,统计每个字母出现的次数(sDic.get(ch, 0)当字典中无该键时,自动创建并取值为0);
之后便是遍历字符串t,若遍历到的字符并不在字典当中,也就是新添加的字母,这时给它默认为0(sDic.get(ch, 0)),则值为0时返回此字符;
若遍历的字母在字典中,则在其值上减去1,若新添加的字母与之前字符串中有重复,则会出现该字符值不断减1后到达0,还有一个该字母,这时因其值已经等于0,返回。
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.
A:
class Solution(object): def findTheDifference(self, s, t): """ :type s: str :type t: str :rtype: str """ sDic = {} for ch in s: sDic[ch] = sDic.get(ch, 0) + 1 for ch in t: if sDic.get(ch, 0) == 0: return ch else: sDic[ch] -= 1
主要思路:
先for遍历字符串s,统计每个字母出现的次数(sDic.get(ch, 0)当字典中无该键时,自动创建并取值为0);
之后便是遍历字符串t,若遍历到的字符并不在字典当中,也就是新添加的字母,这时给它默认为0(sDic.get(ch, 0)),则值为0时返回此字符;
若遍历的字母在字典中,则在其值上减去1,若新添加的字母与之前字符串中有重复,则会出现该字符值不断减1后到达0,还有一个该字母,这时因其值已经等于0,返回。
相关文章推荐
- LeetCode笔记:389. Find the Difference
- 位操作-leetcode 389 Find the Difference
- [leetcode]: 389. Find the Difference
- [LeetCode] 389.Find the Difference
- LeetCode 389. Find the Difference 题解(C++)
- leetcode:bits:Find the Difference(389)
- leetcode389. Find the Difference
- leetcode-389. Find the Difference
- leetcode 389. Find the Difference
- LeetCode-136. Single Number 389. Find the Difference
- 【python】【leetcode】【算法题目389—Find the Difference】
- LeetCode 389: Find the Difference 题解
- 【LeetCode】389. Find the Difference
- [LeetCode]389. Find the Difference(找不同)
- [leetcode] 389. Find the Difference 解题报告
- Leetcode 389 Find the Difference
- leetcode 389. Find the Difference
- leetcode(87).389. Find the Difference
- LeetCode 389. Find the Difference
- LeetCode之389. Find the Difference