Skip to content

Commit b9f955e

Browse files
committed
🎉 #1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence
1 parent cd6fdad commit b9f955e

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/*
2+
* @Author: Goog Tech
3+
* @Date: 2020-08-29 17:48:14
4+
* @LastEditTime: 2020-08-29 17:48:33
5+
* @Description: https://leetcode-cn.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/
6+
* @FilePath: \leetcode-googtech\#1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence\Solution.java
7+
* @WebSite: https://algorithm.show/
8+
*/
9+
10+
class Solution {
11+
public int isPrefixOfWord(String sentence, String searchWord) {
12+
// 切割字符串并将其转化为字符数组
13+
String[] strs = sentence.split(" ");
14+
// 获取检索词的长度
15+
int length = searchWord.length();
16+
// 遍历字符数组
17+
for(int i = 0; i < strs.length; i++) {
18+
// 判断当前字符元素的长度是否大于检索词的长度,并且切割后的字符元素是否与检索词相同
19+
if(strs[i].length() >= length && strs[i].substring(0, length).equals(searchWord)) {
20+
// 若相同则返回句子 sentence 中该单词所对应的下标(下标从 1 开始)
21+
return i + 1;
22+
}
23+
}
24+
// 无果
25+
return -1;
26+
}
27+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
'''
2+
Author: Goog Tech
3+
Date: 2020-08-29 17:48:18
4+
LastEditTime: 2020-08-29 17:48:41
5+
Description: https://leetcode-cn.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/
6+
FilePath: \leetcode-googtech\#1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence\Solution.py
7+
WebSite: https://algorithm.show/
8+
'''
9+
10+
class Solution(object):
11+
def isPrefixOfWord(self, sentence, searchWord):
12+
"""
13+
:type sentence: str
14+
:type searchWord: str
15+
:rtype: int
16+
"""
17+
# 切割字符串并将其转化为字符数组
18+
words = sentence.split(' ')
19+
# 遍历字符数组
20+
for i in range(len(words)):
21+
# 判断当前字符元素的长度是否大于检索词的长度,并且切割后的字符元素是否与检索词相同
22+
if len(words[i]) >= len(searchWord) and words[i][0 : len(searchWord)] == searchWord:
23+
# 若相同则返回句子 sentence 中该单词所对应的下标(下标从 1 开始)
24+
return i + 1
25+
# 无果
26+
return -1

0 commit comments

Comments
 (0)