LeetCode[383] Ransom Note

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/khy19940520/article/details/77987885
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


本地可运行程序:

#include<iostream>
#include<vector>
using namespace std;

bool canConstruct(string ransomNote, string magazine);
/*
解题思路是统计两个字符串中每个字母出现的次数,创建一个
含有26个元素初始值为0的向量用来记录字母出现的次数,
比如a[0]记录的是"a"出现的次数,magazine中出现一次"a",
则a[0] = a[0]+1,ransomNote中出现一次"a",则a[0]=a[0]-1,
最后统计向量中有无小于1的值,小于1说明magazine中某个字母
出现的次数小于ransomNote中该字母出现的次数,ransomNote不能
由magazine中的字母来表示,相反没有小于1的值则可以表示。
有小于1的值则返回false,无则返回true。
*/
int main()
{
	string ransomNote="abababa";
	string  magazine="abababac";
	bool result;
	result = canConstruct(ransomNote, magazine);
	cout << result << endl;
	system("pause");
	return 0;
}

bool canConstruct(string ransomNote, string magazine)
{
	bool result;
	vector<int> charcount(26, 0);//创建向量
	//统计magazine中每个字母出现的次数,向量中相应索引位置的值加1
	for (int i = 0; i < magazine.size(); i++)
	{
		charcount[magazine[i] - 'a']++;
	}
	//统计ransomNote中每个字母出现的次数,向量中相应索引位置的值减1
	for (int i = 0; i < ransomNote.size(); i++)
	{
		charcount[ransomNote[i] - 'a']--;
	}
	//统计向量中有无小于1的元素,有则返回false,无则返回true
	for (int i = 0; i < ransomNote.size(); i++)
	{
		if (charcount[ransomNote[i] - 'a'] < 0)
		{
			return false;
		}
	}
	return true;
}

提交程序(思路与上面刚好相反):

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) 
    {
        vector<int> charcount(26,0);
        for (int i=0;i<ransomNote.size();i++)
        {
            charcount[ransomNote[i]-'a']++;
        }
        for (int i=0;i<magazine.size();i++)
        {
            charcount[magazine[i]-'a']--;
        }
        for (int i=0;i<ransomNote.size();i++)
        {
            if(charcount[ransomNote[i]-'a']>0)
            {
                return false;
            }
        }
        return true;
        
    }
};





猜你喜欢

转载自blog.csdn.net/khy19940520/article/details/77987885