美文网首页
Leetcode 学习 28. Implement strStr

Leetcode 学习 28. Implement strStr

作者: 02d3e536271b | 来源:发表于2018-06-29 16:39 被阅读0次

    给定字符串 haystackneddle,在haystack中找出needle字符串的出现的第一个位置 ,不存在返回 -1

    两个指针:i, j
    i 指向haystack,j 指向needle
    ij 同时移动匹配
    j移动到最后一位匹配成功 则返回i
    若中间任意一位匹配失败,则移动i重新从下一位开始匹配

    public int strStr(String haystack, String needle) {
      for (int i = 0; ; i++) {
        for (int j = 0; ; j++) {
          //needle全部匹配
          if (j == needle.length()) return i; 
          //已经不可能匹配
          if (i +needle.length == haystack.length()) return -1;
          //匹配中有不相等的,直接break i++
          if (needle.charAt(j) != haystack.charAt(i + j)) break;
        }
      }
    }
    

    相关文章

      网友评论

          本文标题:Leetcode 学习 28. Implement strStr

          本文链接:https://www.haomeiwen.com/subject/gbbayftx.html