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;
          
        }
    }
  • 相关阅读:
    HDU 1711
    HDU 4135
    HDU 4462
    HDU 1969
    flask的nocache防止js不刷新
    python2.x里unicode错误问题
    使用SwingWork反而阻塞SwingUI
    利用JProfile 7分析内存OOM
    编译android的一些坑
    java jmenu的替代方案
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4631464.html
Copyright © 2011-2022 走看看