leetcode -- 383

383. Ransom Note

Problem Description

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

Solution Method

Method One

一开始题目理解错了,先去重了。其实不应该这样。方法一直接暴力法解决

int partition_sum(char *a,int low,int high)
{
    int pivot=a[low];
    while(low<high){
        while(low<high&&a[high]>=pivot)high--;
        a[low]=a[high];
        while(low<high&&a[low]<=pivot)low++;
        a[high]=a[low];
    }
    a[low]=pivot;
    return low;
}
void quickSort_sum(char *a,int low,int high)
{
    if(low<high){
        int pivotpos=partition_sum(a,low,high);
        quickSort_sum(a,low,pivotpos-1);
        quickSort_sum(a,pivotpos+1,high);
    }
}
// 去重
void duplicateRemoval(char * s)
{
    int count = 0, i;
    quickSort_sum(s, 0, strlen(s)-1);   // 排序
    for (i = 1; i < strlen(s); i ++)
    {
        while (s[i] == s[i-1])
        { count ++; i ++;}
        s[i-count] = s[i];
    }
    s[i-count] = '\0';
}

bool canConstruct(char * ransomNote, char * magazine)
{
		// 后面发现不用去重
//    duplicateRemoval(ransomNote);
//    duplicateRemoval(magazine);
    if (strlen(ransomNote) == 0 && strlen(magazine) == 0)
        return true;
    if (strlen(magazine) == 0)
        return false;
    for (int i = 0; i < strlen(ransomNote); i ++)
    {
        for (int j = 0; j < strlen(magazine); j ++)
        {
            if (ransomNote[i] == magazine[j])
            {
                char temp;
                temp = magazine[0];
                magazine[0] = magazine[j];
                magazine[j] = temp;
                magazine ++;
                break;
            }
            if (j == strlen(magazine) - 1)
                return false;
        }
    }
    return true;
}

在这里插入图片描述

Method Two

hash解决

bool canConstruct(char * ransomNote, char * magazine){
    int hashArray[26]={0};//模拟HASH

    int i,j,length1=strlen(ransomNote),length2=strlen(magazine),length=0;
    if(length1==0)
    return true;
    if(length1>length2)
    return false;
    for(j=0;j<length2;j++)
    {   
        if(j<length2)
            hashArray[magazine[j]-'a']++;//记录第二个字符串中的元素的个数
    }
    for(i=0;i<length1;i++)
    {
        hashArray[ransomNote[i]-'a']--;
        if(hashArray[ransomNote[i]-'a']<0)
        return false;
    }
    return true;
}

在这里插入图片描述

发布了184 篇原创文章 · 获赞 253 · 访问量 34万+

猜你喜欢

转载自blog.csdn.net/williamgavin/article/details/104608238
今日推荐