짬뽕얼큰하게의 맨땅에 헤딩 :: Check If a Word Occurs As a Prefix of Any Word in a Sentence

Leetcode Problem:

Summary

  • Check if a search word is a prefix of any word in a sentence.

Approach

  • The approach used is to split the sentence into individual words and then check each word to see if it matches the search word
  • If a match is found, the index of the word is returned
  • If no match is found, -1 is returned.

Complexity

  • O(n*m) where n is the number of words in the sentence and m is the length of the search word.

Explanation

  • The solution code starts by splitting the sentence into individual words and storing them in a vector
  • Then it iterates over each word and checks if it matches the search word
  • If a match is found, the index of the word is returned
  • If no match is found, -1 is returned
  • The time complexity of this solution is O(n*m) because it needs to iterate over each word in the sentence and each character in the search word.

Solution Code:


class Solution {
public:
    vector words;
    int isPrefixOfWord(string sentence, string searchWord) {
        words.push_back(sentence);
        for(int i =0; i < sentence.size(); i++){
            if(sentence[i] == ' '){
                words.push_back(sentence.substr(i+1));
            }
        }
        for(int i = 0 ; i < words.size(); i++){
            int j = 0;
            for( ; j < searchWord.size(); j++){
                if(searchWord[j] != words[i][j]){
                    break;
                }
            }
            if(j == searchWord.size()){
                return i + 1;
            }
        }
        return -1;
    }
};

'알고리즘' 카테고리의 다른 글

Make String a Subsequence Using Cyclic Increments  (0) 2025.02.24
Adding Spaces to a String  (0) 2025.02.24
Check If N and Its Double Exist  (0) 2025.02.24
Valid Arrangement of Pairs  (0) 2025.02.24
Minimum Obstacle Removal to Reach Corner  (0) 2025.02.24
블로그 이미지

짬뽕얼큰하게

,