首页 > 其他 > 详细

【Lintcode】013.strStr

时间:2017-06-06 23:03:21      阅读:265      评论:0      收藏:0      [点我收藏+]

题目:

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!