• 【字符串】检查单词是否为句中其他单词的前缀


    题目描述

    给你一个字符串 sentence 作为句子并指定检索词为 searchWord ,其中句子由若干用 单个空格 分隔的单词组成。请你检查检索词 searchWord 是否为句子 sentence 中任意单词的前缀。

    如果searchWord 是某一个单词的前缀,则返回句子sentence 中该单词所对应的下标(下标从 1 开始)。如果 searchWord 是多个单词的前缀,则返回匹配的第一个单词的下标(最小下标)。如果 searchWord 不是任何单词的前缀,则返回 -1 。

    字符串 s 的 前缀 是 s 的任何前导连续子字符串。

    示例 1:

    输入:sentence = "i love eating burger", searchWord = "burg"
    输出:4
    解释:"burg" 是 "burger" 的前缀,而 "burger" 是句子中第 4 个单词。

    解题思路 

    这是一道简单题,核心就是对字符串进行分割和前缀判断,思路如下:

    1. 对字符串进行分割,String strs[] = sentence.split(" ");
    2. 遍历字符串数组,如果数组中对元素是使用searchWord作为前缀,则返回这个下标位置+1;

    代码实现如下:

    1. class Solution {
    2. public int isPrefixOfWord(String sentence, String searchWord) {
    3. String strs[] = sentence.split(" ");
    4. for (int i = 0; i < strs.length; i++) {
    5. if (strs[i].startsWith(searchWord)) {
    6. return i + 1;
    7. }
    8. }
    9. return -1;
    10. }
    11. public static void main(String[] args) {
    12. Solution solution = new Solution();
    13. System.out.println(solution.isPrefixOfWord("i love eating burger", "burg"));
    14. }
    15. }

    接着如果不使用库函数,我自己做字符串处理,思路如下:

    • 对字符串进行分割,如果遇到空格则下标加1,记录为count;
    • 接着获取字符串并且将这个字符串的每个字符和searchWord的每个字符做比较,如果是前缀则返回count;

    注释和代码实现思路如下:

    1. class Solution2 {
    2. public int isPrefixOfWord(String sentence, String searchWord) {
    3. char[] chars = sentence.toCharArray();
    4. // 单词小标从1开始
    5. int count = 1;
    6. for (int i = 0; i < chars.length; ) {
    7. // 计算单词的下标
    8. if (chars[i] == ' ') {
    9. count++;
    10. i++;
    11. }
    12. // 判断是否是前缀
    13. int temp = i;
    14. int sameCount = 0;
    15. for (; i < chars.length && chars[i] != ' '; i++) {
    16. if (i - temp < searchWord.length() && chars[i] == searchWord.charAt(i - temp)) {
    17. sameCount++;
    18. }
    19. }
    20. if (sameCount == searchWord.length()) {
    21. return count;
    22. }
    23. }
    24. return -1;
    25. }
    26. public static void main(String[] args) {
    27. Solution2 solution = new Solution2();
    28. System.out.println(solution.isPrefixOfWord("i love eating burger", "burg"));
    29. }
    30. }

    总结

    这道题2种解法时间复杂度是O(n),预期是第二种实现方式耗时更低,因为不用先处理字符串,再做字符串匹配,实际从测试结果来看耗时基本一样。当然如果有更加简洁、高效的思路欢迎回复。

  • 相关阅读:
    Spring Boot 统一数据返回格式
    桶装水订水小程序app,线上预约订水更便捷
    React18组件一键转换Vue3组件
    使用枚举Enum代替Integer类型
    .gitignore
    LeetCode 6222. 美丽整数的最小增量
    如何获取淘宝/天猫商品历史价格信息的API接口
    JumpServer未授权访问漏洞 CVE-2023-42442
    贺同学 9 月总结
    [vite] Failed to load source map for */*.css.js
  • 原文地址:https://blog.csdn.net/weiliuhong1/article/details/126448094