LeetCode
来源:互联网 发布:淘宝店铺运营推广方案 编辑:程序博客网 时间:2024/06/15 14:25
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:
Input:s = "abcd"t = "abcde"Output:eExplanation:'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,返回。
阅读全文
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- Java POI 设置Excel单元格的宽度和高度
- 算法导论学习笔记17_9_7
- 2017.8.7测试 题四 WJ的逃离
- 客户机/服务器一对一通信模型
- Linux中用Nginx和FTP搭建图片服务器
- LeetCode
- HDU3549 Flow Problem 【网络流E-K算法模板】
- 【14】vue.js — 自定义标签
- 数据库之数据类型
- 陷入迷茫
- python文件传输之粘包问题
- 写在前面
- 无分类编址(超网)中的网络前缀
- 【leetcode】633. Sum of Square Numbers(Python & C++)