码迷,mamicode.com
首页 > 其他好文 > 详细

【Lintcode】013.strStr

时间:2017-06-06 23:26:24      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:++   out   blog   tco   class   get   nec   ane   null   

题目:

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.

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 your confirm with the interviewer first.
Example

If source = "source" and target = "target", return -1.

If source = "abcdabcdefg" and target = "bcd", return 1.

题解:

Solution 1 ()

class Solution {
public:
    int strStr(const char *source, const char *target) {
        if (source == NULL || target == NULL) {
            return -1;
        }
        int len1 = strlen(source);
        int len2 = strlen(target);
        for (int i = 0, j = 0; i < len1 - len2 + 1; i++) {
            for (j = 0; j < len2; j++) {
                if (source[i + j] != target[j]) {
                    break;
                }
            }
            if (j == len2) {
                return i;
            }
        }
        return -1;
    }
};

 

【Lintcode】013.strStr

标签:++   out   blog   tco   class   get   nec   ane   null   

原文地址:http://www.cnblogs.com/Atanisi/p/6953832.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!