每日一道Leetcode算法——Ransom Note——2019.01.28

中文:

给定一个任意赎金票据字符串和另一个包含所有杂志字母的字符串,
写一个函数,如果赎金票据字符串可以从杂志上构建,它将返回true;
否则,它将返回false。
杂志字符串中的每个字母只能在赎金票据中使用一次。
注意:
您可以假设两个字符串仅包含小写字母。
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

英文:

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

解题思路:

这道题的意思是传入两个字符串a和b作为参数,如果字符串b中包含字符串a中所有的字母,则返回true,否则返回false。

将两个字符串按字母拆分,分别查找第一个字符串a中的字母是否在第二个字符串b中存在。

存在则将其变为大写字母A,防止二次使用。不存在则直接返回false。

package cn.leetcode.easy;

/**
 * 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.
 *
 * @author kimtian
 * @date 2091.01.28
 * @num 383题
 */
public class RansomNote {
    public static boolean canConstruct(String ransomNote, String magazine) {
        //将赎金字符串按字母拆分,转化成char数组
        char[] ransomNotes = ransomNote.toCharArray();
        //将杂志字符串按字母拆分,转化成char数组
        char[] magazines = magazine.toCharArray();
        //如果赎金字符串为空,则直接返回true
        if (ransomNotes.length == 0 || ransomNote == "") {
            return true;
        }
        //如果杂志字符串为空,则直接返回false
        if (magazines.length == 0 || magazine == "") {
            return false;
        }
        /**
         * 循环赎金字符串的每个字母,查看其在杂志字符串中是否有相同的值,
         * 因为每个字母只能用一次,而且字符串中只包含小写字母。
         * 所以如果查找存在相同的字母,我们将其转化成A,防止二次使用
         */
        for (int i = 0; i < ransomNotes.length; i++) {
            int j = 0;
            while (j < magazines.length) {
                //当一直没有相对应的字母,循环到杂志字符串的最后一个字母还不相同时,直接终止返回false
                if (magazines[j] != ransomNotes[i] && j == magazines.length - 1) {
                    return false;
                }
                //所以如果查找存在相同的字母,我们将其转化成A,防止二次使用
                if (magazines[j] == ransomNotes[i]) {
                    magazines[j] = 'A';
                    //直接更改j值,跳出循环
                    j = magazines.length;
                    break;
                } else {
                    j++;
                }
            }
        }
        return true;
    }

    /**
     * 测试
     *
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(canConstruct("a", "b"));

    }
}

猜你喜欢

转载自blog.csdn.net/third_/article/details/86679227