zoukankan      html  css  js  c++  java
  • [leetcode-389-Find the Difference]

    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.

    思路:

    用一个map统计s里的字符情况,然后遍历t,将map里对应的字符的出现次数-1。如果没有在map里说明就是要找的字符。

    如果有重复的字符,则会出现负数情况,遍历即可。思路很简单,就是费空间,待优化。

    char findTheDifference(string s, string t)
         {
             map<char, int>str;
             for (int i = 0; i < s.size();i++)
             {
                 str[s[i]]++;
             }
             for (int i = 0; i < t.size();i++)
             {
                 if (str.count(t[i])) str[t[i]]--;             
                 else return t[i];
             }
             map<char, int>::iterator it;
             for (it = str.begin(); it != str.end();it++)
             {
                 if (it->second < 0) return it->first;
             }
         }
  • 相关阅读:
    第一阶段站立会议4
    第一阶段站立会议3
    用户场景描述
    第一阶段站立会议2
    第一阶段站立会议1
    第七周进度条
    第十二周工作总结
    寻找水王
    第十一周工作总结
    构建之法阅读笔记05
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6847248.html
Copyright © 2011-2022 走看看