头条新闻 免费下载夫唯老师seo
不要用珍宝装饰自己,而要用健康武装身体

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。

解答:java
public class Solution {public int strStr(String haystack, String needle) {if (needle.isEmpty()) {return 0;}int index = haystack.indexOf(needle);return index;}public static void main(String[] args) {Solution solution = new Solution();String haystack1 = "sadbutsad";String needle1 = "sad";int result1 = solution.strStr(haystack1, needle1);System.out.println(result1); // 输出 0String haystack2 = "leetcode";String needle2 = "leeto";int result2 = solution.strStr(haystack2, needle2);System.out.println(result2); // 输出 -1}
}
