Given a
You have to check if
Return the index of the word in
If
A prefix of a string
sentence
that consists of some words separated by a single space, and a searchWord
.You have to check if
searchWord
is a prefix of any word in sentence
.Return the index of the word in
sentence
where searchWord
is a prefix of this word (1-indexed).If
searchWord
is a prefix of more than one word, return the index of the first word (minimum index). If there is no such word return -1.A prefix of a string
S
is any leading contiguous substring of S
.Example 1:
Input: sentence = "i love eating burger", searchWord = "burg"
Output: 4
Approach
Java
import java.util.ArrayList;import java.util.List;public class CheckPrefixWord {public static void main(String[] args) {String sentence = "i love eating burger";String searchWord = "burg";System.out.println(isPrefixOfWord(sentence, searchWord));}static int isPrefixOfWord(String s, String t) {List<String> v = new ArrayList<String>();int n = s.length();int i = 0;while (i < n) {String str = "";while (i < n && s.charAt(i) == ' ')i++;while (i < n && s.charAt(i) != ' ') {str += s.charAt(i);i++;}i++;v.add(str);}int index = -1;for (int i1 = 0; i1 < v.size(); i1++) {String str = v.get(i1);int flag = 0;int len = str.length();if (len >= t.length()) {for (int j = 0; j < t.length(); j++) {if (t.charAt(j) != str.charAt(j)) {flag = 1;break;}}if (flag == 0) {index = i1 + 1;break;}}}return index;}}
C++
#include <bits/stdc++.h>using namespace std;int isPrefixOfWord(string s, string t){vector<string> v;int n = s.size();int i = 0;while (i < n){string str = "";while (i < n && s[i] == ' ')i++;while (i < n && s[i] != ' '){str += s[i];i++;}i++;v.push_back(str);}int index = -1;for (int i = 0; i < v.size(); i++){string str = v[i];int flag = 0;int len = str.size();if (len >= t.size()){for (int j = 0; j < t.size(); j++){if (t[j] != str[j]){flag = 1;break;}}if (flag == 0){index = i + 1;break;}}}return index;}int main(){string sentence = "i love eating burger";string searchWord = "burg";cout << isPrefixOfWord(sentence, searchWord);return 0;}
No comments:
Post a Comment