算法设计与结构基础作业第七周

本文介绍两道编程题的解决方案:一是通过对比两个字符串找出被添加的字符;二是判断是否能从一组杂志中构建出勒索信。两题均采用计数法解决,通过对字符出现次数的统计来实现目标。

389.Find the Difference

Description:

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.

分析:
   首先要确定不能被这一个样例哄骗了。s是随机产生的,t在s的基础上加上一个字母,字母的位置也是随机的。

My C++ code:

class Solution {
public:
    char findTheDifference(string s, string t){
        int m = s.length() ;
        int n = t.length() ;
        char res ;
        vector<int> letter(26, 0) ;
        for(int i = 0 ; i < m ; i ++)
        {
            letter[s[i] - 'a'] ++ ; 
        }
        for(int i = 0 ; i < n ; i ++)
        {
            letter[t[i] - 'a'] -- ;
        }
        for(int i = 0 ; i < 26 ; i ++)
        {
            if(letter[i] < 0)
            {
                res = i + 'a';
                break ;
            }
        }
        return res ;
    }
};

383.Ransom Note

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

分析:
   套路和上一道题目是一样的,注意要分清楚magazines和randsomNote。

My C++ code:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值