1 - 从strStr谈面试技巧与代码风格
13.字符串查找
要求:如题
思路:(自写AC)双重循环,内循环读完则成功
还可以用Rabin,KMP算法等
public int strStr(String source, String target) { if (source == null || target == null) { return -1; } char[] sources = source.toCharArray(); char[] targets = target.toCharArray(); int m = sources.length; int n = targets.length; for (int i = 0; i <= m - n; i++) { int j = 0; while (j < n && sources[i + j] == targets[j]) { j++; } if (j == n) { return i; } } return -1; }