链接:https://leetcode.cn/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/solution/by-xun-ge-v-wavw/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
解题思路
题意需要判断字符串是否为总字符串其中一个字符串的前缀,根据'空格'进行划分,直接根据题意进行模拟,按'空格'对字符串进行分割,然后判断是否为其前缀即可
代码注释超级详细
- int isPrefixOfWord(char * sentence, char * searchWord){
- int s_len = strlen(sentence);
- int w_len = strlen(searchWord);
- int i = 0;
- int index = 1;
- //处理最前面的字符串是否相等
- for(i; sentence[i] != ' ' && i < s_len; i++)
- {
- int j = 0;
- int m = i;
- while(i == 0 && j < w_len)
- {
- if(sentence[m] != searchWord[j])
- {
- break;
- }
- m++;
- j++;
- }
- if(j == w_len)
- return index;
- }
- //后面按' '进行划分字符串并比较
- for(i; i < s_len; ++i)
- {
- if(sentence[i] == ' ')
- {
- index++;
- int j = 0;
- int m = i+1;
- while(j < w_len)
- {
- if(sentence[m] != searchWord[j])
- {
- break;
- }
- m++;
- j++;
- }
- if(j == w_len)
- return index;
- }
- }
- return -1;
- }
-
- 作者:xun-ge-v
- 链接:https://leetcode.cn/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/solution/by-xun-ge-v-wavw/
- 来源:力扣(LeetCode)
- 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。