wupangyen / LeetCode

LeetCode
1 stars 0 forks source link

LeetCode 1961. Check If String Is a Prefix of Array #8

Open wupangyen opened 3 years ago

wupangyen commented 3 years ago

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.

wupangyen commented 3 years ago

Example :

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

wupangyen commented 3 years ago

loop through all the words in the array create a new String variable each iteration concatenate the word in the new string and compare the give s and our new_string

if they are equal return true;

if exit out the loop didn't return true it means string s is not a prefix string of words

we return false

wupangyen commented 3 years ago

class Solution { public boolean isPrefixString(String s, String[] words) {

    String new_string = "";

    for(String word:words){
        new_string = new_string + word;
        if(new_string.equals(s)){
            return true;

        }

    }
    return false;

}

}