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

问题;

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

如果 source = "source" 和 target = "target",返回 -1

如果 source = "abcdabcdefg" 和 target = "bcd",返回 1

答案很简单利用String中的一个str.indexof(str)就可以轻松得到。

public static int strStr(String source, String target) {
        // write your code here
    if(source==null||target==null) {
    return -1;
    }
    int index1 = source.indexOf(target);
return index1;
    }
    public static void main(String[] args) {
    String A = “abcdefghij”;
    String B = "bd";
        System.out.println(strStr(A,B));
    }

猜你喜欢

转载自blog.csdn.net/javaisnotgood/article/details/79453426