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
 

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        StringBuilder sb = new StringBuilder();
        sb.append(magazine);
        int length = ransomNote.length(), count = 0;
        for(int i=0;i<length;i++){
            int index = sb.indexOf(ransomNote.charAt(i)+"");
            if(index != -1){
                sb.delete(index, index+1);
                count++;
            }
        }
        System.out.println(count+" cnt "+length+" lnt");
        if(count == length){
            return true;
        }
        return false;
    }
}
 
 
Try it on Leetcode

Here, we are going to solve using StringBuilder. Append Magazine string to StringBuilder.

1) For each character in ransomNote, we are going to find that character using indexOf.
2) If index is not -1, then particular character is found in string, which means if index is -1, then that character is not in a string. [For using indexOf, we must use only in form of string in StringBuilder]
3) Now, we are going to remove that character using index. We are using start index as index and end index as index+1, where it is neglected and removes character at that index  and increment count.

Finally if count is equal to length of ransomNote then it is true, else false.

Related Posts:

Click here for May month challenges with solution and explanation
Click here for April month challenges with solution and explanation


Please let us know your views in comment section

Subscribe us to receive updates instantly..

Happy Coding..!!

Comments

Popular posts from this blog

Balanced Binary Tree

First Unique Character in a String

Majority Element

Smallest Range II