zoukankan      html  css  js  c++  java
  • Implement strStr()

    Implement strStr().

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

    New version: 4ms

     1 class Solution {
     2 public:
     3     int strStr(string haystack, string needle) {
     4         int result = 0;
     5         int lenN = needle.size(), lenH = haystack.size();
     6         if(lenN == 0 && lenH == 0) return 0;
     7         if(lenN == 0) return 0;
     8         if(lenH < lenN) return -1;
     9         
    10         for(int i = 0; i <= lenH - lenN; i++){
    11             if(haystack[i] == needle[0]){
    12                 int index = 0, move = i;
    13                 while(move < lenH && index < lenN && haystack[move] == needle[index]){
    14                     move++;
    15                     index++;
    16                 }
    17                 if(index == lenN) return i;
    18             }
    19         }
    20         return -1;
    21     }
    22 };

    Analyse: Pay special attention to when the length of haystack is less  than that of needle, and the case that needle is empty.

     1 class Solution {
     2 public:
     3     int strStr(string haystack, string needle){
     4         int index = -1;
     5         if(haystack.length() < needle.length()) return index;
     6         else if(needle.length() == 0) return 0;
     7         
     8         for(int j = 0; j <= haystack.length() - needle.length(); j++){
     9             int index_needle = 0;
    10             if(haystack[j] == needle[index_needle]){
    11                 index = j;
    12                 for(int k = 1; k < needle.length(); k++){
    13                     if(haystack[j+k] != needle[index_needle+k]){
    14                         index = -1;
    15                         break;
    16                     }
    17                 }
    18             }
    19             if(index >= 0) return index;
    20         }
    21         return index;
    22     }
    23 };
  • 相关阅读:
    改变字符串里面多个颜色
    悬浮按钮
    改变一串字体的多个颜色
    iOS上如何让按钮文本左对齐问题
    Swift中的willSet与didSet
    Swift语法之 ---- ?和!区别
    UIButton文字的显示位置,字体的大小
    javaweb要点复习 jsp和servlet
    常量指针和指针常量
    判断括号序列的合法性
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4439241.html
Copyright © 2011-2022 走看看