LeetCode 389. Find the Difference
来源:互联网 发布:农村网络消费研究报告 编辑:程序博客网 时间:2024/04/27 18:05
题意
两个字符串s,t,都是小写字母,t由s中的字符和新增的一个字母随机排列组合而成,找出新增的字符!
思路
最直接的思路是HashMap,根据字符串s建立一个HashMap,key是字母,value是字母出现的次数(因为新增的字母可能本来有),再对字符串t中的每一个字符,判断是否在HashMap中,如果t中字符在HashMap中不存在,则显然是那个不同的字符。如果在HashMap中,将该字符对应的value减1,在某一步,value小于0,说明该字符在t中出现的次数比s中多一次,显然就是新增的那个字符。
Java
public class Solution { public char findTheDifference(String s, String t) { //HashMap不能使用基本数据类型 //Map<char,int> s_strmap = new HashMap<char,int>(); Map<Character,Integer> s_strmap = new HashMap<Character,Integer>(); int i; char result = '0'; for(i = 0;i < s.length();i ++) { //hashmap中没有该字符,字符作为key,出现次数置1放入map //if(s_strmap.get(s.charAt(i)) == null) if(s_strmap.containsKey(s.charAt(i)) == false) { //放入该字符,value设置为0 s_strmap.put(s.charAt(i),1); } else { //hashmap中存在该字符,出现次数value++ //s_strmap.get(s.charAt(i))++; s_strmap.put(s.charAt(i),s_strmap.get(s.charAt(i))+1); } } for(i = 0;i < t.length();i ++) { //如果t中字符在HashMap中不存在,则显然是那个不同的字符 if(s_strmap.get(t.charAt(i)) == null) result = t.charAt(i); else { //更新HashMap,将value-1 s_strmap.put(t.charAt(i),s_strmap.get(t.charAt(i))-1); //判断value是否小于0,如果<0,说明重复的字符中t中多了一个 if(s_strmap.get(t.charAt(i)) < 0) result = t.charAt(i); } } return result; }}
ps:Solutions有两种更好的思路,根据s和t中只有一个字母不同,用位运算或者ASCII码解决,记下以供学习
ASCII码
public char findTheDifference(String s, String t) { int charCode = t.charAt(s.length()); // Iterate through both strings and char codes for (int i = 0; i < s.length(); ++i) { charCode -= (int)s.charAt(i); charCode += (int)t.charAt(i); } return (char)charCode; //结果转为char返回 }
bit manipulation
public char findTheDifference(String s, String t) { int n = t.length(); char c = t.charAt(n - 1); for (int i = 0; i < n - 1; ++i) { c ^= s.charAt(i); c ^= t.charAt(i); } 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
- 389.[LeetCode]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
- DL学习笔记【19】nn包中的各位Modules
- 使用okHttp发起请求并用fastJson解析
- java学习笔记-04
- 最小二乘法
- 从零开始搭建一个简易的服务器(二)
- LeetCode 389. Find the Difference
- 有源蜂鸣器和无源蜂鸣器
- 华为OJ训练之0010-161231-挑7
- spring 第9天 Resurce 资源访问
- 新增删除removeChild
- Java笔记之二
- The next day of study notes
- 微软笔试-Numberic Keypad
- File类和时间类的两道综合练习