zoukankan      html  css  js  c++  java
  • LeetCode: 389 Find the Difference(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:

    Input:
    s = "abcd"
    t = "abcde"
    
    Output:
    e
    
    Explanation:
    'e' is the letter that was added.

    代码:

    自己的:

    1 class Solution {
    2 public:
    3     char findTheDifference(string s, string t) {
    4         sort(s.begin(), s.end());
    5         sort(t.begin(), t.end());
    6         auto r = mismatch(s.begin(), s.end(), t.begin());
    7         return (*r.second);
    8     }
    9 };

    别人的(1):

     1 class Solution {
     2 public:
     3     char findTheDifference(string s, string t) {
     4         // Similar to single number. Can do using hashmap...
     5         int charmap[26] = {0};
     6         for(char c: t) {
     7             charmap[c-'a']++;
     8         }
     9         // Iterate over s, one letter will have count 1 left
    10         for(char c: s) {
    11             charmap[c-'a']--;
    12         }
    13         for(int i=0;i<26;i++) {
    14             if (charmap[i] == 1)
    15                 return 'a'+i;
    16         }
    17         return -1;
    18     }
    19 };

    别人的(2):

     1 class Solution {
     2 public:
     3     char findTheDifference(string s, string t) {
     4         char res = 0;
     5         for(auto c: s) 
     6             res^=c;
     7         for(auto c: t) 
     8             res^=c;
     9         return res;
    10     }
    11 };
  • 相关阅读:
    Maven简介
    Activiti核心API
    Activiti数据库支持
    使用idea进行activiti工作流开发入门学习
    Activiti 工作流
    枚举其他用法
    枚举类的基本使用
    kotlin中抽象类
    kotlin中接口
    kotlin 类的继承
  • 原文地址:https://www.cnblogs.com/llxblogs/p/7477678.html
Copyright © 2011-2022 走看看