【leetcode】P28ImplementStrstr
//實現 strStr() 函式。
//
// 給定一個 haystack 字串和一個 needle 字串,在 haystack 字串中找出 needle 字串出現的第一個位置 (從0開始)。如
//果不存在,則返回 -1。
//
// 示例 1:
//
// 輸入: haystack = "hello", needle = "ll"
//輸出: 2
//
//
// 示例 2:
//
// 輸入: haystack = "aaaaa", needle = "bba"
//輸出: -1
//
//
// 說明:
//
// 當 needle 是空字串時,我們應當返回什麼值呢?這是一個在面試中很好的問題。
//
// 對於本題而言,當 needle 是空字串時我們應當返回 0 。這與C語言的 strstr() 以及 Java的 indexOf() 定義相符。
// Related Topics 雙指標 字串
// ? 610 ? 0
package leetcode.editor.cn;
//Java:實現 strStr()
public class P28ImplementStrstr {
public static void main(String[] args) {
Solution solution = new P28ImplementStrstr().new Solution();
// TO TEST
int i = solution.strStr("hello", "ll");
System.out.println(i);
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int strStr(String haystack, String needle) {
if (needle == null || needle.length() == 0)
return 0;
for (int i = 0; i <= haystack.length() - needle.length(); i++) {
if (haystack.substring(i, i + needle.length()).equals(needle))
return i;
}
return -1;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
相關文章
- 【LeetCode】如何學習LeetCode?LeetCode
- leetcodeLeetCode
- LeetCode in actionLeetCode
- leetcode 238LeetCode
- LeetCode 164 最大間距 HERODING的LeetCode之路LeetCode
- LeetCode 143 重排連結串列 HERODING的LeetCode之路LeetCode
- LeetCode問題LeetCode
- 【LeetCode】Jewels and StonesLeetCode
- Leetcode 513 javascriptLeetCodeJavaScript
- LeetCode 162 JavascriptLeetCodeJavaScript
- Leetcode 921 JavascriptLeetCodeJavaScript
- [Leetcode] Edit DistanceLeetCode
- LeetCode 克隆圖LeetCode
- LeetCode #378 JavaScriptLeetCodeJavaScript
- LeetCode 747 JavaScriptLeetCodeJavaScript
- Leetcode725LeetCode
- LeetCode 53 JSLeetCodeJS
- LeetCode 50 JSLeetCodeJS
- Leetcode03LeetCode
- LeetCode 799 JavaScriptLeetCodeJavaScript
- leetcode690LeetCode
- [LeetCode] Group AnagramLeetCode
- [LeetCode] Rotate StringLeetCode
- LeetCode 283 jsLeetCodeJS
- Leetcode #463 JavascriptLeetCodeJavaScript
- Leetcode # 495 JavascriptLeetCodeJavaScript
- Leetcode 229 JavaScriptLeetCodeJavaScript
- golang刷leetcodeGolangLeetCode
- Leetcode目錄LeetCode
- LeetCode:快速排序LeetCode排序
- leetcode Sum系列LeetCode
- LeetCode三則LeetCode
- LeetCode2:LeetCode
- The best LeetCode NodesLeetCode
- LeetCode兩則LeetCode
- Leetcode學習LeetCode
- leetcode no.1LeetCode
- leetcode開篇LeetCode