1455. 检查单词是否为句中其他单词的前缀『简单』

题目来源于力扣(LeetCode

一、题目

1455. 检查单词是否为句中其他单词的前缀

题目相关标签:字符串

提示:

  • 1 <= sentence.length <= 100
  • 1 <= searchWord.length <= 10
  • sentence 由小写英文字母和空格组成。
  • searchWord 由小写英文字母组成。
  • 前缀就是紧密附着于词根的语素,中间不能插入其它成分,并且它的位置是固定的——-位于词根之前。(引用自 前缀_百度百科 )

二、解题思路

  1. 调用 startsWith()indexOf() 方法来判断单词 searchWord 是否为单词的前缀

三、代码实现

// indexOf() 方法实现
public static int isPrefixOfWord(String sentence, String searchWord) {
    int len = searchWord.length();
    String[] words = sentence.split(" ");
    // 从前往后遍历,第一个即是最靠前的结果
    for (int i = 0; i < words.length; i++) {
        // 排除元素长度小于 searchWord 的情况
        if (words[i].length() < len) {
            continue;
        }
        // 调用 indexOf 方法
        int k = words[i].indexOf(searchWord);
        if (k == 0) {
            return i + 1;
        }
    }
    return -1;
}

// startsWith() 方法实现
public static int isPrefixOfWord2(String sentence, String searchWord) {
    String[] words = sentence.split(" ");
    for (int i = 0; i < words.length; i++) {
        // 调用 startsWith 方法
        if (words[i].startsWith(searchWord)) {
            return i + 1;
        }
    }
    return -1;
}

四、执行用时

五、部分测试用例

public static void main(String[] args) {
    String sentence = "i love eating burger", searchWord = "burg";  // output:4
//    String sentence = "this problem is an easy problem", searchWord = "pro";  // output:2
//    String sentence = "i am tired", searchWord = "you";  // output:-1
//    String sentence = "i use triple pillow", searchWord = "pill";  // output:4
//    String sentence = "hello from the other side", searchWord = "they";  // output:-1

    int result = isPrefixOfWord(sentence, searchWord);
    System.out.println(result);
}
原文地址:https://www.cnblogs.com/zhiyin1209/p/13080911.html