zoukankan      html  css  js  c++  java
  • [leedcode 28] Implement strStr()

    Implement strStr().

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

    public class Solution {
        public int strStr(String haystack, String needle) {
            //此题解法,外层循环haystack,每一位与needle进行比较。两层for循环
            //注意flag需要重新置位
            //注意外层循环的范围,不需要循环到最后一位,只要循环到倒数第二个字符串长度即可
            if(needle.length()==0) return 0;
            if(haystack.length()==0) return -1;
             
            int lenH=haystack.length();
            int lenN=needle.length();
            boolean flag=true;
            for(int i=0;i<=lenH-lenN;i++){
                if(haystack.charAt(i)==needle.charAt(0)){
                     /* int temp=i+1;
                      for(int j=1;j<lenN;j++){
                          if(haystack.charAt(temp)!=needle.charAt(j)){
                               flag=false;
                              break;
                             
                          }else{
                              temp++;
                          }
                      }*/
                      for(int j=0;j<lenN;j++){
                          if(haystack.charAt(j+i)!=needle.charAt(j)){
                              flag=false;
                              break;
                              
                          }
                          
                      }
                      ////////////////
                      if(flag){
                          return i;
                      }
                      flag=true;//置位
               
                }
      
            }
            return -1;
          
        }
    }
  • 相关阅读:
    iframe跨页面调用函数
    $.extend()
    tab标签 插件 by 腾讯 jianminlu
    click事件多次触发 jQuery
    vertical-align
    display:inline-block
    在父页面访问iframe的东西
    2019牛客多校第三场
    2019HDU多校第一场
    2019江苏省赛
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4631464.html
Copyright © 2011-2022 走看看