【LeetCode算法-28/35】Implement strStr()/Search Insert Position

LeetCode第28题

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

翻译:

返回大字符串中第一次找到给定小字符串的下标

思路:

String有自带API:indexOf

代码:

class Solution {
    public int strStr(String haystack, String needle) {
        return haystack.indexOf(needle);
    }
}

我们来看下SDK源码

复制代码
public int indexOf(String str) {
    return indexOf(str, 0);
}

public int indexOf(String str, int fromIndex) {
    return indexOf(this, str, fromIndex);
}

static int indexOf(String source,
                   String target,
                   int fromIndex) {
    if (fromIndex >= source.count) {
        return (target.count == 0 ? source.count : -1);
    }
    if (fromIndex < 0) {
        fromIndex = 0;
    }
    if (target.count == 0) {
        return fromIndex;
    }

    char first = target.charAt(0);
    int max = (source.count - target.count);

    for (int i = fromIndex; i <= max; i++) {
        /* Look for first character. */
        if (source.charAt(i)!= first) {
            while (++i <= max && source.charAt(i) != first);
        }

        /* Found first character, now look at the rest of v2 */
        if (i <= max) {
            int j = i + 1;
            int end = j + target.count - 1;
            for (int k = 1; j < end && source.charAt(j)
                     == target.charAt(k); j++, k++);

            if (j == end) {
                /* Found whole string. */
                return i;
            }
        }
    }
    return -1;
}
复制代码

思路也很简单和暴力,就是遍历对比字符 

 

LeetCode第35题

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 4:

Input: [1,3,5,6], 0
Output: 0

翻译:

给定一个有序数组和一个给定值,在数组中找到这个值所在的下标;如果没有这个值,那么返回他应该插入的下标位置

思路:

和选择排序或插入排序思路相似,就是将定值和已经排好序的数组遍历比较大小

代码:

复制代码
class Solution {
    public int searchInsert(int[] nums, int target) {
        int j= 0;
        for(int i = 0;i<nums.length;i++){
            if(nums[i] < target){
                j++;
            }
        }
        return j;
    }
}
复制代码

如果数组元素比给定值要小,那么J就+1;如果数组元素比给定值要大,J不操作;那么下标比J小的元素值就比给定值要小,即J就是我们所需要的下标

欢迎关注我的微信公众号:安卓圈

posted @   嘉禾世兴  阅读(157)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2017-05-09 【转载】TabLayout 源码解析
2017-05-09 【转载】AsyncTask源码分析
2017-05-09 强引用、弱引用、软引用、虚引用
点击右上角即可分享
微信分享提示