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 s, String[] 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++;} elsereturn false;}}}if (k == s.length())return true;return false;}}
C++
#include <bits/stdc++.h>using namespace std;bool isPrefixString(string s, vector<string> &words){int k = 0;string str = "";for (int i = 0; i < words.size() && k < s.size(); i++){str += words[i];if (str.size() > s.size())return false;else{for (int j = 0; j < words[i].size(); j++){if (s[k] == words[i][j]){k++;}elsereturn false;}}}if (k == s.size())return true;return false;}int main(){string s = "iloveleetcode";vector<string> words = {"i", "love", "leetcode", "apples"};if (isPrefixString(s, words))cout << "true\n";elsecout << "false\n";return 0;}
No comments:
Post a Comment