LeetCode 383. Ransom Note

来源:互联网 发布:centos 7.0 安装cacti 编辑:程序博客网 时间:2024/06/14 00:20

题目 :
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

思路:
先分别计算ransomNote和magazine的长度,如果ransomNote的长度大,直接返回false。如果ransomNote的长度大,直接返回false; 如果在magazine中找到第一个ransomNode[i],如果这个位置不是字符串中的最后(不过npos一般是-1),就将magazine中这个索引对应的字符删掉,继续循环,否则返回false。如果循环结束没有返回false,就可以构建,返回true。

代码:

class Solution {public:    bool canConstruct(string ransomNote, string magazine) {        int lenran=ransomNote.length();//分别计算ransomNote和magazine的长度        int lenmag=magazine.length();        if(lenran>lenmag){//如果ransomNote的长度大,直接返回false            return false;        }        for(int i=0;i<lenran;++i){//遍历ransomNote            int index=magazine.find_first_of(ransomNote[i]);//如果在magazine中找到第一个ransomNode[i]            if(index!=string::npos){//如果这个位置不是字符串中的最后(不过npos一般是-1)                magazine.erase(index,1);//就将magazine中这个索引对应的字符删掉,继续循环                continue;            }            else{//否则返回false                return false;            }        }        return true;//如果循环结束没有返回false,就可以构建,返回true    }};

**输出结果:*42ms

0 0