1. 程式人生 > >[LeetCode] 28. 實現 strStr() 函式 —— javascript

[LeetCode] 28. 實現 strStr() 函式 —— javascript

28. 實現 strStr() 函式。 給定一個 haystack 字串和一個 needle 字串,在 haystack 字串中找出 needle 字串出現的第一個位置 (從0開始)。如果不存在,則返回 -1。

	var strStr = function(haystack, needle) {
	    if (needle=='') return 0;
	    var len2 = needle.length;
	    var len = haystack.length - len2;
	    for (var i = 0; i<=len; i++) {
	        if (
haystack.substring(i, i+len2) == needle) { return i; } } return -1; };