LeetCode.389 Find the Difference
来源:互联网 发布:国内贸易用什么软件 编辑:程序博客网 时间:2024/05/18 14:25
题目:
分析2(原创-易理解):
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; }}
阅读全文
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
- 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.389 Find the Difference
- Leetcode:Find the Difference
- Find the Difference --LeetCode
- LeetCode Find the Difference
- [LeetCode] Find the Difference
- [Leetcode] Find the Difference
- bzoj3671[Noi2014]随机数生成器(贪心)
- VSM及SMO算法小结
- java-资源类以及等待和唤醒
- 用gdb调试程序笔记: 以段错误(Segmental fault)为例
- Linux 常用命令
- LeetCode.389 Find the Difference
- SVN解决Unable to connect to a repository at URL 禁止访问 (forbidden)
- iOS图文并排demo,图文混排,UITextView图文显示,html转NSAttributedString
- jvm调优
- jquery的each()详细介绍
- 技术分享连载(四十一)
- 构造方法的简单说明
- 嵌入式Linux USB驱动开发之教你一步步编写USB驱动程序
- jpa建一个枚举类型---Hibernate注解之@Enumerated