|
| 1 | +## 1455. 检查单词是否为句中其他单词的前缀 |
| 2 | +> https://leetcode-cn.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/ |
| 3 | +
|
| 4 | + |
| 5 | +### Java |
| 6 | +```java |
| 7 | +/* |
| 8 | + * @Author: Goog Tech |
| 9 | + * @Date: 2020-08-29 17:48:14 |
| 10 | + * @LastEditTime: 2020-08-29 17:48:33 |
| 11 | + * @Description: https://leetcode-cn.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/ |
| 12 | + * @FilePath: \leetcode-googtech\#1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence\Solution.java |
| 13 | + * @WebSite: https://algorithm.show/ |
| 14 | + */ |
| 15 | + |
| 16 | +class Solution { |
| 17 | + public int isPrefixOfWord(String sentence, String searchWord) { |
| 18 | + // 切割字符串并将其转化为字符数组 |
| 19 | + String[] strs = sentence.split(" "); |
| 20 | + // 获取检索词的长度 |
| 21 | + int length = searchWord.length(); |
| 22 | + // 遍历字符数组 |
| 23 | + for(int i = 0; i < strs.length; i++) { |
| 24 | + // 判断当前字符元素的长度是否大于检索词的长度,并且切割后的字符元素是否与检索词相同 |
| 25 | + if(strs[i].length() >= length && strs[i].substring(0, length).equals(searchWord)) { |
| 26 | + // 若相同则返回句子 sentence 中该单词所对应的下标(下标从 1 开始) |
| 27 | + return i + 1; |
| 28 | + } |
| 29 | + } |
| 30 | + // 无果 |
| 31 | + return -1; |
| 32 | + } |
| 33 | +} |
| 34 | +``` |
| 35 | + |
| 36 | +### Python |
| 37 | +```python |
| 38 | +''' |
| 39 | +Author: Goog Tech |
| 40 | +Date: 2020-08-29 17:48:18 |
| 41 | +LastEditTime: 2020-08-29 17:48:41 |
| 42 | +Description: https://leetcode-cn.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/ |
| 43 | +FilePath: \leetcode-googtech\#1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence\Solution.py |
| 44 | +WebSite: https://algorithm.show/ |
| 45 | +''' |
| 46 | + |
| 47 | +class Solution(object): |
| 48 | + def isPrefixOfWord(self, sentence, searchWord): |
| 49 | + """ |
| 50 | + :type sentence: str |
| 51 | + :type searchWord: str |
| 52 | + :rtype: int |
| 53 | + """ |
| 54 | + # 切割字符串并将其转化为字符数组 |
| 55 | + words = sentence.split(' ') |
| 56 | + # 遍历字符数组 |
| 57 | + for i in range(len(words)): |
| 58 | + # 判断当前字符元素的长度是否大于检索词的长度,并且切割后的字符元素是否与检索词相同 |
| 59 | + if len(words[i]) >= len(searchWord) and words[i][0 : len(searchWord)] == searchWord: |
| 60 | + # 若相同则返回句子 sentence 中该单词所对应的下标(下标从 1 开始) |
| 61 | + return i + 1 |
| 62 | + # 无果 |
| 63 | + return -1 |
| 64 | +``` |
0 commit comments