LeetCode笔记:383. Ransom Note

来源:互联网 发布:oracle 数据库迁移 编辑:程序博客网 时间:2024/06/08 09:10

问题:

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

大意:

给出一个任意的勒索信字符串和另一个的包含所有从杂志中来的字母的字符串,写一个函数,如果勒索信可以被杂志重构得到则返回true;否则返回false。
杂志中的每个字母都只能被使用一次。
注意:
你可以假设字符串都只包含小写字母。
canConstruct(“a”, “b”) -> false
canConstruct(“aa”, “ab”) -> false
canConstruct(“aa”, “aab”) -> true

思路:

  1. 首先想到的一个思路是以各个地在magazine中寻找note中的字母,找到一个则删去一个,若有找不到的就是false了,若找到最后一个都找到了,则是true了。
  2. 第一个思路做出来后,运行时间高达91ms,想来是每个字母的寻找过程都比较耗时,于是参照以前的经验,对于这种全是小写字母进行比较字符串的,还是可以拿两个26位的数字数组来存储两个字符串中每个字母找到的个数,然后去比较两个数字数组中的数字,不同的是,这里要比较的是note对应的数组中,不为0的字母位置的数字,在magazine数组中的数字是否大于note中的数字,注意是大于而不是等于,因为目的是magazine可以拼出note来,而不是完全相同,这样一来耗时迅速减少到了17ms,优化很明显。

代码(Java):

第一种方法:

public class Solution {    public boolean canConstruct(String ransomNote, String magazine) {        char[] noteArr = new char[ransomNote.length()];        noteArr = ransomNote.toCharArray();        for (int i = 0; i < noteArr.length; i++) {            if (magazine.indexOf(noteArr[i]) == -1) return false;            else {                int position = magazine.indexOf(noteArr[i]);                String before = magazine.substring(0, position);                String after = magazine.substring(position+1, magazine.length());                magazine = before.concat(after);            }        }        return true;    }}

第二种方法:

public class Solution {    public boolean canConstruct(String ransomNote, String magazine) {        char[] noteArr = new char[ransomNote.length()];        noteArr = ransomNote.toCharArray();        char[] magazineArr = new char[magazine.length()];        magazineArr = magazine.toCharArray();        // int数组默认会初始化为全为0        int[] noteLetter = new int[26];        int[] magazineLetter = new int[26];        for (int i = 0; i < noteArr.length; i++) {            int position = noteArr[i] - 'a';            noteLetter[position]++;        }        for (int i = 0; i < magazineArr.length; i++) {            int position = magazineArr[i] - 'a';            magazineLetter[position]++;        }        for (int i = 0; i < 26; i++) {            if (noteLetter[i] != 0 && noteLetter[i] > magazineLetter[i]) return false;        }        return true;    }}

版权所有:http://blog.csdn.net/cloudox_

0 0