Skip to content

1961. Check If String Is a Prefix of Array 👍

  • Time: $O(\Sigma |\texttt{words[i]}|
  • Space: $O(\Sigma |\texttt{words[i]}|
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  bool isPrefixString(string s, vector<string>& words) {
    string prefix;
    for (const string& word : words) {
      prefix += word;
      if (prefix == s)
        return true;
    }
    return false;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public boolean isPrefixString(String s, String[] words) {
    StringBuilder sb = new StringBuilder();
    for (final String word : words) {
      sb.append(word);
      // Do not call `toString()` unless the length matches.
      if (sb.length() == s.length() && sb.toString().equals(s))
        return true;
    }
    return false;
  }
}
1
2
3
4
5
6
7
8
class Solution:
  def isPrefixString(self, s: str, words: list[str]) -> bool:
    prefix = []
    for word in words:
      prefix.append(word)
      if ''.join(prefix) == s:
        return True
    return False