• Java实现 LeetCode 383 赎金信


    383. 赎金信

    给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串ransom能不能由第二个字符串magazines里面的字符构成。如果可以构成,返回 true ;否则返回 false。

    (题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。)

    注意:

    你可以假设两个字符串均只含有小写字母。

    canConstruct(“a”, “b”) -> false
    canConstruct(“aa”, “ab”) -> false
    canConstruct(“aa”, “aab”) -> true

    PS:

    String.indexof(a,b)
    从b索引开始找a字符

    class Solution {
       public boolean canConstruct(String ransomNote, String magazine) {
            if (ransomNote.length() > magazine.length()) {
                return false;
            }
            int[] chars = new int[26];
            for (int i = 0; i < ransomNote.length(); i++) {
                char c = ransomNote.charAt(i);
                int index = magazine.indexOf(c, chars[c - 'a']);
                if (index == -1) {
                    return false;
                }
                chars[c - 'a'] = index + 1;
            }
            return true;
        }
    }
    
  • 相关阅读:
    LeetCode数据库178
    LeetCode数据库181
    LeetCode数据库177
    LeetCode数据库176
    HNOI2003 消防局的设立
    HNOI2001 产品加工
    Luogu P1020 关路灯
    NOIP2004 虫食算
    SP2713 GSS4-Can you answer these queries IV
    APIO2008 免费道路
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12946529.html
Copyright © 2020-2023  润新知