leetcode 389. Find the Difference 牛人用异或 或者 求和 解决,很简单。

た 入场券 2022-07-17 04:09 208阅读 0赞

389. Find the Difference

Question Editorial Solution

My Submissions

  • Total Accepted: 7465
  • Total Submissions: 14609
  • Difficulty: Easy

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:

  1. Input:
  2. s = "abcd"
  3. t = "abcde"
  4. Output:
  5. e
  6. Explanation:
  7. 'e' is the letter that was added.

我的解法:利用hashmap进行记录

  1. public class Solution {
  2. public char findTheDifference(String s, String t){
  3. Map map=new HashMap<Character,Integer>();
  4. for(int i=0;i<s.length();i++){
  5. if(!map.containsKey(s.charAt(i)))
  6. map.put(s.charAt(i),1);
  7. else{
  8. int temp = (int)map.get(s.charAt(i));
  9. map.put(s.charAt(i),++temp);
  10. }
  11. }
  12. for(int a=0;a<t.length();a++){
  13. if(!map.containsKey(t.charAt(a))){
  14. return t.charAt(a);
  15. }
  16. else{
  17. int temp = (int)map.get(t.charAt(a));
  18. temp--;
  19. if(temp<0)return t.charAt(a);
  20. map.put(t.charAt(a),temp);
  21. }
  22. }
  23. return ' ';
  24. }
  25. }

牛人解法:

java 用异或:

  1. public char findTheDifference_B(String s, String t) {
  2. char c = 0;
  3. for (int i = 0; i < s.length(); ++i) {
  4. c ^= s.charAt(i);
  5. }
  6. for (int i = 0; i < t.length(); ++i) {
  7. c ^= t.charAt(i);
  8. }
  9. return c;
  10. }

或者用求和,c:

  1. char findTheDifference(char* s, char* t) {
  2. int sum1=0,sum2=0;
  3. for(;*s;s++)
  4. sum1+=*s;
  5. for(;*t;t++)
  6. sum2+=*t;
  7. return sum2-sum1;
  8. }

发表评论

表情:
评论列表 (有 0 条评论,208人围观)

还没有评论,来说两句吧...

相关阅读