LintCode 13. 文字列検索

質問リンク: https://www.lintcode.com/problem/implement-strstr/description?_from=ladder&&fromId=1

これは単純な質問です。

しかし、基礎が弱くて何度も提出しました。

説明する

指定されたソース文字列とターゲット文字列について、  ソース文字列内のターゲット文字列の最初のインデックス (0 から) を出力する必要があります。

ターゲットがソースに存在しない場合は、単に を返します -1

説明する

実際の面接では KMP アルゴリズムを実装する必要がありますか?

  • 必要はありません。実際の面接でこの問題に遭遇した場合、面接官は単にあなたの基本的な実装能力をテストしたいだけかもしれません。ただし、必ず最初に面接官に確認してください。

サンプル

例 1:

Input: source = "source" ,target = "target"
Output: -1	
Explanation: If the source does not contain the target content, return - 1.

例 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.

チャレンジ

O(n2) は許容されます。O(n) アルゴリズムを実装できますか? (ヒント:  KMP )

 

この問題は O(n2) で解決できます。KMP アルゴリズムは名前付きのアルゴリズムなのであまり広く使われていないため、現時点ではここで学習して使用することは考えられていません(将来的には言いにくいですが…)。

私の解決策:

class Solution:
    """
    @param source: 
    @param target: 
    @return: return the index
    """
    def strStr(self, source, target):
        # Write your code here
        #j = 0
        if(target == ''):
            return 0
        for k in range(len(source)):
            j = 0
            for i in range(len(target)):
                if(k+i >= len(source)):  #没有必要的写法。可以参考下方题解。
                    break
                if(source[k+i]!=target[j]):
                    break
                j = j + 1
            if(j==len(target)):
                return k
        return -1

9 章の参考質問の解決策:

# 本参考程序来自九章算法,由 @九章算法 提供。版权所有,转发请注明出处。
# - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
# - 现有的面试培训课程包括:九章算法班,系统设计班,算法强化班,Java入门与基础算法班,Android 项目实战班,
# - Big Data 项目实战班,算法面试高频题班, 动态规划专题班
# - 更多详情请见官方网站:http://www.jiuzhang.com/?source=code


class Solution:
    def strStr(self, source, target):
        if source is None or target is None: #判空。显然比我的target=''的写法要好些
            return -1
        len_s = len(source)
        len_t = len(target)
        for i in range(len_s - len_t + 1): #这样的写法会更好一些。
            j = 0
            while (j < len_t):               
                if source[i + j] != target[j]:
                    break
                j += 1
            if j == len_t:
                return i
        return -1

 

おすすめ

転載: blog.csdn.net/zjy997/article/details/104098112