码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_383 Ransom Note(String)

时间:2017-05-03 17:16:47      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:++   put   letters   cas   ash   struct   other   string   pre   

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
给定两个字符串,判断前一个字符串能否由后一个字符串构成,后一个字符串中的字符只能使用一次。

solution1:定义一个长度为26的数组,对应26个字母

 java中默认整数数组自动赋值为0

public class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        int[] arr=new int[26];
        for(int i=0;i<magazine.length();i++){
            arr[magazine.charAt(i)-‘a‘]++;
        }
        for(int i=0;i<ransomNote.length();i++){
            if(--arr[ransomNote.charAt(i)-‘a‘]<0){
                return false;
            }
        }
        return true;
    }
}

solution2:hashmap

public class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        Map<Character, Integer> map= new HashMap<>();
        for (char c:magazine.toCharArray()){
            int count = magM.getOrDefault(c, 0)+1;
            map.put(c, count);
        }
        for (char c:ransomNote.toCharArray()){
            int count = map.getOrDefault(c,0)-1;
            if (count<0)
                return false;
            map.put(c, count);
        }
        return true;
    }
}

 

leetcode_383 Ransom Note(String)

标签:++   put   letters   cas   ash   struct   other   string   pre   

原文地址:http://www.cnblogs.com/ytq1016/p/6802190.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!