Saturday, July 4, 2015

leetcode 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.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button to reset your code definition.

基础考题: 求一个字符串中的子串,需要注意的是在循环条件的判断,是 <=, 还是 ==,什么时候要加 ==, 什么时候不加也可以,这些在循环条件判断的时候都要留心,最简单的测试方式是取一个最简单的case,比如下题中,如果haystack "a",needle “a”, 肯定是返回 0, 但是如果不加==,就会返回-1,所以在面试过程中,写完跟面试官说写好之前,特别注意循环条件的判断,加不加==????? 非常重要!

class Solution {
public:
    int strStr(string haystack, string needle) {
        //sanity check
        if (haystack.size() < needle.size()) return -1;
        for (int i = 0; i + needle.size() <= haystack.size(); i++) {
            int j = 0;
            for (; j < needle.size(); j++) {
                if (haystack[i+j] != needle[j]) break;
            }
            if (j == needle.size()) return i;
        }
        return -1;
    }
};

No comments:

Post a Comment