Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
分析:
给出两个字符串,查询第二个字符串是否在第一个字符串中出现过,如果有,就返回第一次出现的位置。
If source = "source"
and target = "target"
, return -1
.
If source = "abcdabcdefg"
and target = "bcd"
, return 1
.
public class Solution { public int strStr(String haystack, String needle) { if (haystack == null || needle == null){ return -1; } for (int i = 0; i < haystack.length() - needle.length() + 1; i++){ int j = 0; for (j = 0; j < needle.length(); j++){ if (haystack.charAt(i + j) != needle.charAt(j)){ break; } } if (j == needle.length()){ return i; } } return -1; } }