LeetCode 28 Implement strStr() (实现找子串函数)

 
Problem : 实现找子串的操作:如果没有找到则返回-1  ,如果找到则返回第一个匹配位置第一个字符的下标
 
遍历操作,依次遍历子串中的元素,从长串的第i个元素位置开始,当成功遍历结束子串所有元素时,返回此时的i即时所求结果,
如果此时的i+j已经等于长串的个数,那么表示没有找到,返回-1 
 
参考代码:
package leetcode_50;


/***
 * 
 * @author pengfei_zheng
 * 实现找子串的功能
 */
public class Solution28 {
    public int strStr(String haystack, String needle) {
         for (int i = 0; ; i++) {
            for (int j = 0; ; j++) {
              if (j == needle.length()) return i;
              if (i + j == haystack.length()) return -1;
              if (needle.charAt(j) != haystack.charAt(i + j)) break;
           }
        }
    }
}
原文地址:https://www.cnblogs.com/zpfbuaa/p/6527396.html