leetcode383. Ransom Note

题目

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

假设有一组字母和一组从杂志中获取的字母,问是否能够用从杂志中获取的字母构成想要的那组字母,要求每个单词只能使用一次。

思路一

使用索引为字母的数组来存储该字母还剩下几个没有从杂志中找到。每从杂志中找到一个字母,对应字母位置上的数字减一,每遇到一个字母则该字母位置上的数字加一。如果没有多余的字母,则说明可以找到足够多的字母拼接。

    public boolean canConstruct(String ransomNote, String magazine) {
        if(ransomNote.isEmpty()) return true;
        if(ransomNote.length() > magazine.length()) return false;
        int p1 = 0, p2 = 0;
        int[] count = new int[26];
        int wordCount = 0;
        while(p1 < ransomNote.length() && p2 < ransomNote.length()) {
            char c1 = ransomNote.charAt(p1);
            char c2 = magazine.charAt(p2);
            if(++count[c1-'a'] == 1) {
                wordCount++;
            }
            if(--count[c2-'a'] == 0) {
                wordCount--;
            }
            
            p1++;
            p2++;
        }
        
        while(p2 < magazine.length()) {
            if(wordCount == 0) break;
            char c = magazine.charAt(p2);
            count[c-'a']--;
            if(count[c-'a'] == 0) {
                wordCount--;
            }
            p2++;
        }
        return wordCount == 0;
    }

思路二:找不到字母就结束

思路二利用java的API来查找magazine中从上一个找到的字母开始,下一个字母所在的位置。如果找不到,则说明无法完成拼接。

    public boolean canConstruct(String ransomNote, String magazine) {
        int len=ransomNote.length();
        int[] index = new int[128];
        for(int i = 0; i < len; i++){
            char cu=ransomNote.charAt(i);
            int result=magazine.indexOf(cu,index[cu]);
            if(result == -1){
                return false;
            }
            else{
                index[cu]=result + 1;   
            }   
        }
        return true;
    }

clipboard.png
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注我的微信公众号!将会不定期的发放福利哦~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值