28. 实现 strStr()

image.png

暴力法

执行用时:1486 ms, 在所有 Java 提交中击败了11.99%的用户 内存消耗:38.3 MB, 在所有 Java 提交中击败了62.53%的用户

  1. class Solution {
  2. public int strStr(String haystack, String needle) {
  3. int n = haystack.length(), m = needle.length();
  4. for (int i = 0; i <= n - m; i++) {
  5. boolean flag = true;
  6. for (int j = 0; j < m; j++) {
  7. if (haystack.charAt(i + j) != needle.charAt(j)) {
  8. flag = false;
  9. break;
  10. }
  11. }
  12. if (flag) return i;
  13. }
  14. return -1;
  15. }
  16. }