Leetcode 28 Implement strStr()
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
Clarification:
What should we return when needle
is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle
is an empty string. This is consistent to C's strstr() and Java's indexOf().
1)
class Solution {
public int strStr(String haystack, String needle) {
if(haystack.length() == 0 && needle.length() == 0){
return 0;
}else if(haystack == null || haystack.length() == 0){
return -1;
}
int index = haystack.indexOf(needle);
if(index > -1){
return index;
}else{
return -1;
}
}
}
2)
class Solution {
public int strStr(String haystack, String needle) {
return (needle.isEmpty() || haystack.indexOf(needle) == 0) ? 0 : haystack.indexOf(needle);
}
}
可以直接使用庫函式或者是自己手動的進行匹配。
相關文章
- leetcode28_Implement strStr()LeetCode
- 【LeetCode 28_字串_匹配】Implement strStr()LeetCode字串
- 【leetcode】28. Implement strStr() 字串匹配KMP BMLeetCode字串匹配KMP
- 【LeetCode從零單排】No28 Implement strStr()LeetCode
- Leetcode Implement strStr()LeetCode
- Leetcode-Implement strStr()LeetCode
- Implement strStr() leetcode javaLeetCodeJava
- [LeetCode] Implement strStr() 實現strStr()函式LeetCode函式
- LeetCode-Implement strStr()-KMPLeetCodeKMP
- Leetcode--28. 實現strStr()(JS版)LeetCodeJS
- LeetCode- Implement Trie (Prefix Tree)LeetCode
- Leetcode Implement Queue using StacksLeetCode
- LeetCode-028-實現 strStr()LeetCode
- LeetCode-Implement Stack Using QueuesLeetCode
- LeetCode-Implement Queue using StacksLeetCode
- LeetCode | 232 Implement Queue Using StacksLeetCode
- 【leetcode】P28ImplementStrstrLeetCode
- leetcode —— 字串相關(28、344)LeetCode字串
- 實現 strStr()
- strstr函式函式
- [LeetCode] 232. 225 Implement Queue/Stack using Stacks/QueuesLeetCode
- KMP演算法(Leetcode第28題)KMP演算法LeetCode
- Implement CGLIB in ABAPCGLib
- Leetcode 225. Implement Stack using Queues 用佇列實現棧LeetCode佇列
- LeetCode 225 Implement Stack using Queues(用佇列來實現棧)(*)LeetCode佇列
- C 庫函式 - strstr()函式
- 【LeetCode 225_資料結構_棧_實現】Implement Stack using QueuesLeetCode資料結構
- leetcode 232. Implement Queue using Stacks 用棧實現佇列(簡單)LeetCode佇列
- 【LeetCode 232_資料結構_佇列_實現】Implement Queue using StacksLeetCode資料結構佇列
- 5. PHP 函式 strstr ()PHP函式
- 演算法strstr實現演算法
- Implement Leader Election Algorithm With GoGo
- 每日一練(37):實現 strStr()
- (函式)實現strstr函式函式
- 子串查詢函式strstr函式
- LintCode-Implement Queue by Stacks
- WPF C# implement scaletransform and translatetransfrom programmaticallyC#ORM
- how to implement speech recognition in J2EE