DEV Community

Jen C.
Jen C.

Posted on

LeetCode - Solution for 383. Ransom Note

Runtime: Beats more than 80% of users with TypeScript

Iterate through each char in the string ransomNote. If you can find the char in the string tempMagazine, remove the char from tempMagazine (indicating that the char has been used by ransomNote). Return false if you cannot find the char in tempMagazine.

function canConstruct(ransomNote: string, magazine: string): boolean {

    let char = '';
    let tempMagazine = magazine;
    for(let i =0; i< ransomNote.length; i+= 1){
        char = ransomNote.charAt(i);

        if(tempMagazine.indexOf(char) > -1) tempMagazine = tempMagazine.replace(char, '');
        else return false;
    }
    return true;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)