Java算法之字符串查找

2021-01-11  本文已影响0人  在海上烧烤

问题描述

对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1。

样例
样例 1:

输入: source = "source" , target = "target"
输出:-1
样例解释: 如果source里没有包含target的内容,返回-1
样例 2:

输入: source = "abcdabcdefg" ,target = "bcd"
输出: 1
样例解释: 如果source里包含target的内容,返回target在source里第一次出现的位置

解法

    public static int fun(String source, String target) {
        int result = -1;

        if (source.length() == 0 || target.length() == 0) {
            return result;
        }
        if (source.length() < target.length()) {
            return result;
        }
        int len = 0;//记住匹配到的长度
        int index = 0;//记住第一个匹配到的索引
        for (int i = 0; i < source.length(); i++) {
            for (int j = 0; j < target.length(); j++) {
                if (source.charAt(i) == target.charAt(j)) {
                    index = i;
                    len++;
                    break;
                }
            }
        }
        if (len == target.length()) {
            //如果长度相等 则得到相应的索引
            return index;
        }
        return result;
    }
上一篇 下一篇

猜你喜欢

热点阅读