Created
February 1, 2013 12:27
-
-
Save kikuchy/4691030 to your computer and use it in GitHub Desktop.
「文字列aの中に文字列bが何回出現するか数えなさい。ただしString.indexOf()を使うならindexOf()を定義しなさい」という課題で書いたもの。もっとちゃんと最適化したい。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var a = "kdindsuqncxkem,dsf"; | |
var b = "ds"; | |
String.prototype.indexOf = function(compStr, offset){ | |
offset = offset || 0; | |
while((this.length - compStr.length) >= offset){ | |
var isCharEq = true; | |
for(var i = 0; i < compStr.length; i++){ | |
if(!(isCharEq &= this[i + offset] === compStr[i])) break; | |
} | |
if(isCharEq) | |
return offset; | |
offset++; | |
} | |
return -1; | |
}; | |
var times = function(a, b){ | |
var isEnd = false; | |
var prevPos = 0; | |
var count = 0; | |
while(!isEnd){ | |
var pos = a.indexOf(b, prevPos); | |
if(pos > -1){ | |
count++; | |
prevPos = pos + 1; | |
}else | |
isEnd = true; | |
} | |
return count; | |
}; | |
console.log(times(a, b)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment