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)  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;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值