28. implement strstr()

题目描述

实现strstr。
给两个字符串a、b,返回b在a中第一次出现的位置,若无,返回-1。

题目分析

两层循环,暴力查找。

代码

#include <iostream>

class Solution {
public:
  int strStr(std::string haystack, std::string needle) {
    int result = -1;
    if (haystack.length() < needle.length()) {
      return -1;
    }
    for (unsigned i = 0; i <= haystack.length() - needle.length(); ++i) {
      unsigned j = 0;
      for ( ; j < needle.length(); ++j) {
        if (haystack[i + j] != needle[j]) {
          break;
        }
      }
      if (j == needle.length()) {
        result = i;
        break;
      }
    }
    return result;
  }
};

总结

细心