Introduction: The task is to test if a given string (s) can be a prefix of a given array (words). It is a String challenge usually asked at programming contests and coding rounds during the job interviews.
Description: 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 else return false.
Algorithmic steps to make the solution:
1. Starting with a blank string (to be populated)
2. Traversing through the array (i.e. named words)
3. Adding per traversed element to the blank array of (1) and comparing if the given string (‘s) matches the currently populated blank string of (1)
4. Return true if 3 is successful
5. Return false if (2) has completed with no success in (3)
6. End of the program
Solution in Swift programming language:
class Solution {
func isPrefixString(_ s: String, _ words: [String]) -> Bool
// string to be populated later to compare
var stringWords = String()
for i in words {
// adding 1 element and checking to see if already has matched, else adding another
stringWords += i
// returning as soon as the so far added prefix ‘stringWords’ has matched ‘s’
if s == stringWords {
return true
}
}
// when no prefix has matched at the end of traversing loop
return false
}
}
Sample test case:
Input: s = “Quranhasmessages”, words = [“Quran”,”has”,”messages”,”mysterious”]
Output: true
Explanation: s can be made by concatenating “Quran”, “has”, and “messages” together.
