Check If String Is a Prefix of Array

Given a string s and an array of strings words, determine whether s is a prefix string of words.

A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length.

Return true if s is a prefix string of words, or false otherwise.

Example 1:

Input: s = "iloveleetcode", words = ["i","love","leetcode","apples"]
Output: true
Explanation:
s can be made by concatenating "i", "love", and "leetcode" together.

Example 2:

Input: s = "iloveleetcode", words = ["apples","i","love","leetcode"]
Output: false
Explanation:
It is impossible to make s using a prefix of arr.

Approach

Java

public class PrefixStringArray {
    public static void main(String[] args) {
        String s = "iloveleetcode";
        String[] words = { "i""love""leetcode""apples" };

        System.out.println(isPrefixString(s, words));
    }

    static boolean isPrefixString(String sString[] words) {

        int k = 0;
        String str = "";
        for (int i = 0; i < words.length && k < s.length(); 
i++) {
            str += words[i];

            if (str.length() > s.length())
                return false;
            else {
                for (int j = 0; j < words[i].length(); j++) {
                    if (s.charAt(k) == words[i].charAt(j)) {
                        k++;
                    } else
                        return false;
                }
            }
        }
        if (k == s.length())
            return true;
        return false;
    }

}

C++

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

bool isPrefixString(string svector<string&words)
{

    int k = 0;
    string str = "";
    for (int i = 0i < words.size() && k < s.size(); i++)
    {
        str += words[i];

        if (str.size() > s.size())
            return false;
        else
        {
            for (int j = 0j < words[i].size(); j++)
            {
                if (s[k] == words[i][j])
                {
                    k++;
                }
                else
                    return false;
            }
        }
    }
    if (k == s.size())
        return true;
    return false;
}
int main()
{
    string s = "iloveleetcode";
    vector<stringwords = {"i""love""leetcode""apples"};

    if (isPrefixString(swords))
        cout << "true\n";

    else
        cout << "false\n";

    return 0;
}


No comments:

Post a Comment