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);
}
}
可以直接使用庫函式或者是自己手動的進行匹配。
相關文章
- 【leetcode】28. Implement strStr() 字串匹配KMP BMLeetCode字串匹配KMP
- Implement strStr()
- Leetcode--28. 實現strStr()(JS版)LeetCodeJS
- LeetCode | 232 Implement Queue Using StacksLeetCode
- LeetCode-028-實現 strStr()LeetCode
- [LeetCode] 232. 225 Implement Queue/Stack using Stacks/QueuesLeetCode
- 【leetcode】P28ImplementStrstrLeetCode
- Leetcode 225. Implement Stack using Queues 用佇列實現棧LeetCode佇列
- Implement CGLIB in ABAPCGLib
- leetcode 232. Implement Queue using Stacks 用棧實現佇列(簡單)LeetCode佇列
- 實現 strStr()
- KMP演算法(Leetcode第28題)KMP演算法LeetCode
- Implement Leader Election Algorithm With GoGo
- C 庫函式 - strstr()函式
- 5. PHP 函式 strstr ()PHP函式
- WPF C# implement scaletransform and translatetransfrom programmaticallyC#ORM
- 每日一練(37):實現 strStr()
- WPF ListBox implement autoscroll via behavior extension and SelectedItem
- WPF datagrid implement multi select via behavior selectionchanged event in MVVMMVVM
- C 標準庫 – string.h之strstr使用
- LeetCode T14 T26 T27 T28 T35LeetCode
- LeetCode題解(Offer28):判斷二叉樹是否左右對稱(Python)LeetCode二叉樹Python
- 28
- [PHP原始碼閱讀]strpos、strstr和stripos、stristr函式PHP原始碼函式
- C語言-字串函式的實現(五)之strstrC語言字串函式
- 5/28
- vue28Vue
- 2024/03/28
- 28-replicationcontrollerController
- APT28APT
- 2024/6/28
- 2024/05/28
- 2018-10-28
- 2018-11-28
- day28-CSSCSS
- 4月28日
- 2020-10-28
- 2020-09-28