Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
就是给一个target 看target里面是否包含另外给定的字符
假设target长度m 匹配长度n, 对target每个长度为n的substring都检查一次 时间O((m- n)* n)= O(m*n)
public class Solution { public int strStr(String haystack, String needle) { if (haystack == null || needle == null || needle.length() == 0) { return 0; } if (needle.length() > haystack.length()) { return -1; } for (int i = 0; i <= haystack.length() - needle.length(); i++) { boolean res = true; for (int j = 0; j < needle.length(); j++) { if (haystack.charAt(i + j) != needle.charAt(j)) { res = false; break; } } if (res == true) { return i; } } return -1; } }
没有评论:
发表评论