[leetcode By Python]strStr
2018-01-28 14:46
441 查看
题目:
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Example 2:
代码+调试:
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll" Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba" Output: -1
代码+调试:
class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ i = 0 while i<len(haystack)-len(needle)+1: h,n = i,0 while n<len(needle) and haystack[h]==needle : h = h+1 n = n+1 if n == len(needle): return i i = i+1 else: return -1 a = Solution() print a.strStr('h','')第一次提交时出现错误,是因为当haystack='x',needle='',我认为应该输出-1,但系统告诉正确答案是0。这是由于我对字符串的理解出现了一点问题
相关文章推荐
- [LeetCode By Python]107. Binary Tree Level Order Traversal II
- [leetcode:python]28.Implement strStr()
- [LeetCode By Python]171. Excel Sheet Column Number
- [Leetcode By Python]69. Sqrt(x)
- [LeetCode By Python]7 Reverse Integer
- [LeetCode By Python]118. Pascal's Triangle
- [leetCode By python]104. Maximum Depth of Binary Tree
- LeetCode 28 Implement strStr() (C,C++,Java,Python)
- [LeetCode BY Python]169. Majority Element
- Leetcode-Implement strStr()-Python
- [LeetCode By Python]108. Convert Sorted Array to Binary Search Tree
- 【LeetCode 28】Implement strStr() (Python)
- [LeetCode BY Python]160. Intersection of Two Linked Lists
- [LeetCode By Python]58. Length of Last Word
- [LeetCode By Python]83. Remove Duplicates from Sorted List
- [LeetCode By Python]119. Pascal's Triangle II
- [LeetCode By Python]66. Plus One
- [LeetCode By Python] 2 Add Two Number
- [leetCode By Python]100. Same Tree
- [leetCode By Python] 14. Longest Common Prefix