For a given source string and a target string, you should output the first index(from 0) of target string in source string.
If target does not exist in source, just return -1
.
If source = "source"
and target = "target"
, return -1
.
If source = "abcdabcdefg"
and target = "bcd"
, return 1
.
1 class Solution { 8 public int strStr(String source, String target) { 9 if (source == null || target == null) return -1; 12 if (target.length() == 0) return 0; 14 if (source.length() < target.length()) return -1; 15 16 for (int i = 0; i < source.length(); i++) { 17 boolean isAllChecked = true; 18 for (int j = 0; j < target.length(); j++) { 19 if (i + j >= source.length() || target.charAt(j) != source.charAt(i + j)) { 20 isAllChecked = false; 21 break; 22 } 23 } 24 25 if (isAllChecked == true) { 26 return i; 27 } 28 } 29 return -1; 30 } 31 }