13. Implement strStr()

13. Implement strStr()

Tag:

String

Description:

For a given source string and a target string, you should output the first index(from 0) of target string in source string.

If target does not exist in source, just return -1.

Have you met this question in a real interview?
Clarification
Do I need to implement KMP Algorithm in a real interview?

Not necessary. When you meet this problem in a real interview, the interviewer may just want to test your basic implementation ability. But make sure you confirm with the interviewer first.
Example
Example 1:

Input: source = “source” ,target = “target”
Output: -1
Explanation: If the source does not contain the target content, return - 1.
Example 2:

Input:source = “abcdabcdefg” ,target = “bcd”
Output: 1
Explanation: If the source contains the target content, return the location where the target first appeared in the source.
Challenge
O(n2) is acceptable. Can you implement an O(n) algorithm? (hint: KMP)

Main Idea:

Basic implementation of String. The main idea is to compare the each element in A with B. If the first char are the same, then compare the next one, until the string B is completely satisfied.

For advanced implement, KMP can reduce it to O(N). Feel free to dive into this.

Time/Space Cost:

Time Cost:   O ( n m ) \ O(nm)

Code:

class Solution {
public:
    /**
     * @param source: 
     * @param target: 
     * @return: return the index
     */
    int strStr(string &source, string &target) {
        // Write your code here
        int len1 = source.length();
        int len2 = target.length();
        if(len2 == 0){
            return 0;
        }
        
        if(len2 > len1 || len1 == 0){
            return -1;
        }
        
        for(int k = 0; k <= len1 - len2; k++){
            int i = k, j = 0;
            while(source[i] == target[j]){
                if(j == len2-1){
                    return k;
                }
                i++;
                j++;
            }
        }
        return -1;
    }
};

发布了28 篇原创文章 · 获赞 1 · 访问量 420

猜你喜欢

转载自blog.csdn.net/Zahb44856/article/details/104083569