码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-383-Ransom Note(以空间换时间)

时间:2018-06-02 14:56:23      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:代码   cte   要求   构造   统计   一个   script   空间   har   

题目描述:

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.

Each letter in the magazine string can only be used once in your ransom note.

Note:
You may assume that both strings contain only lowercase letters.

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true 

 

要完成的函数:

bool canConstruct(string ransomNote, string magazine) 

 

说明:

1、古时候……绑架者会写勒索信,要求给赎金,不然就撕票。但为了不被认出自己的字迹,就会从报纸上剪出文字,拼凑成一封勒索信。这道题给定两个字符串,第一个是绑匪要写的勒索信的字符串,第二个是报纸上能提供的文字的字符串,要求判断能不能从第二个字符串中构建出第一个字符串。

第二个字符串中的每个字母只能用一次,两个字符串中只有小写字母。

2、这道题有三种做法:

①双重循环,第一个字符串碰到一个字符就去找第二个字符串中有没有,这是最慢最没有效率的做法。

②先排序,再比较,这种做法时间复杂度比①小,但也不快。

③以空间换时间,定义一个长度为26的vector,遍历一遍第二个字符串,统计所有字母的出现次数,再遍历一遍第一个字符串,逐个在vector中相应位置上减1。

最后再遍历一遍vector,看是否存在小于0的数值,如果有,返回false。如果没有,返回true。

时间复杂度是O(n)

 

我们采用第三种做法,构造代码如下:

    bool canConstruct(string ransomNote, string magazine) 
    {   
        vector<int>count(26,0);
        for(char i:magazine)//统计第二个字符串中所有的字母出现次数
            count[i-‘a‘]++;
        for(char i:ransomNote)//在对应的位置上减去1
            count[i-‘a‘]--;
        for(int i:count)//遍历一遍vector,看是否存在小于0的数值
        {
            if(i<0)
                return false;
        }
        return true;
    }

上述代码实测24ms,beats 89.66% of cpp submissions。

leetcode-383-Ransom Note(以空间换时间)

标签:代码   cte   要求   构造   统计   一个   script   空间   har   

原文地址:https://www.cnblogs.com/king-3/p/9125327.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!