028,Implement strStr()

https://leetcode.com/problems/implement-strstr/discuss/12807/Elegant-Java-solution

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll" Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba" Output: -1

翻译:

返回出现needle字符串的索引位置,没有的话,返回-1

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;//不相等直接进行外层循环,说明两者的开头字符不相同,如果相同,再进行第二层循环,进行后面的字符比较
    }
  }
}

个人理解:常规思维是for循环的次数都是固定的,上边的代码没有固定,采取依次向前推荐的方法,求解。

测试:字符串长度str.length()

没有判断好break的条件是不相等的

break跳出的是内层循环

双循环中break跳出哪一个循环的问题。

for(int i=1;i<=4;i++){
            for(int j=1;j<=4;j++){
                System.out.println("i="+i+",j="+j);
                break;
            }       
        } 
image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容