Maximum Number of Words You Can Type

There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.

Given a string text of words separated by a single space (no leading or trailing spaces) and a string brokenLetters of all distinct letter keys that are broken, return the number of words in text you can fully type using this keyboard.

Example 1:

Input: text = "hello world", brokenLetters = "ad"
Output: 1
Explanation: We cannot type "world" because the 'd' key is broken.

Example 2:

Input: text = "leet code", brokenLetters = "lt"
Output: 1
Explanation: We cannot type "leet" because the 'l' and 't' keys are broken.

Example 3:

Input: text = "leet code", brokenLetters = "e"
Output: 0
Explanation: We cannot type either word because the 'e' key is broken.

Approach

Java

import java.util.HashSet;

public class MaximumNumberWords {
    public static void main(String[] args) {

        String text = "hello world", brokenLetters = "ad";

        System.out.println(canBeTypedWords(text, brokenLetters));

    }

    static int canBeTypedWords(String text
String brokenLetters) {

        HashSet<Characterst = new HashSet<>();
        for (int i = 0; i < brokenLetters.length(); i++) {
            st.add(brokenLetters.charAt(i));
        }

        int i = 0;
        int flag = 0;
        int cnt = 0;
        int n = text.length();
        while (i < n) {
            flag = 0;
            while (i < n && text.charAt(i) == ' ')
                i++;
            while (i < n && text.charAt(i) != ' ') {
                if (st.contains(text.charAt(i))) {
                    flag = 1;
                }
                i++;
            }
            if (flag == 0)
                cnt++;
        }

        return cnt;
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

int canBeTypedWords(string textstring brokenLetters)
{

    set<charst;
    for (int i = 0i < brokenLetters.size(); i++)
    {
        st.insert(brokenLetters[i]);
    }

    int i = 0;
    int flag = 0;
    int cnt = 0;
    int n = text.size();
    while (i < n)
    {
        flag = 0;
        while (i < n && text[i] == ' ')
            i++;
        while (i < n && text[i] != ' ')
        {
            if (st.find(text[i]!= st.end())
            {
                flag = 1;
            }
            i++;
        }
        if (flag == 0)
            cnt++;
    }

    return cnt;
}

int main()
{
    string text = "hello world"brokenLetters = "ad";

    cout << canBeTypedWords(textbrokenLetters<< "\n";

    return 0;
}


No comments:

Post a Comment