yin*_*jia 10 javascript recursion repeat
我想知道是否有办法检查字符串中的重复字符而不使用双循环.这可以通过递归来完成吗?
使用双循环的代码示例(如果字符串中有重复的字符,则返回true或false):
var charRepeats = function(str) {
for(var i = 0; i <= str.length; i++) {
for(var j = i+1; j <= str.length; j++) {
if(str[j] == str[i]) {
return false;
}
}
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
提前谢谢了!
the*_*d47 16
这将:
function isIsogram (str) {
return !/(.).*\1/.test(str);
}
Run Code Online (Sandbox Code Playgroud)
win*_*ner 12
(在这个答案的最后可以找到一个递归解决方案.)
您可以使用javascript builtin Array函数对某些 MDN进行一些参考
var text = "test".split("");
text.some(function(v,i,a){
return a.lastIndexOf(v)!=i;
});
Run Code Online (Sandbox Code Playgroud)
回调参数:
v 迭代的当前值
i迭代的 当前索引
是 当前数组.split("") 从一个字符串创建一个数组
.some(function(v,i,a){...}) 通过一个数组直到该函数returns true,并且立即结束.(如果之前找到匹配项,则不会遍历整个数组)可以在此处找到某些功能的详细信息
测试,有几个字符串:
var texts = ["test", "rest", "why", "puss"];
for(var idx in texts){
var text = texts[idx].split("");
document.write(text + " -> " + text.some(function(v,i,a){return a.lastIndexOf(v)!=i;}) +"<br/>");
}
//tested on win7 in chrome 46+Run Code Online (Sandbox Code Playgroud)
如果需要递归.
递归更新:
//recursive function
function checkString(text,index){
if((text.length - index)==0 ){ //stop condition
return false;
}else{
return checkString(text,index + 1)
|| text.substr(0, index).indexOf(text[index])!=-1;
}
}
// example Data to test
var texts = ["test", "rest", "why", "puss"];
for(var idx in texts){
var txt = texts[idx];
document.write( txt + " ->" + checkString(txt,0) + "<br/>");
}
//tested on win7 in chrome 46+Run Code Online (Sandbox Code Playgroud)
您可以使用.indexOf()和.lastIndexOf()来确定索引是否重复。意思是,如果该字符的第一次出现也是最后一次出现,那么您就知道它不会重复。如果不是真的,那么它会重复。
var example = 'hello';
var charRepeats = function(str) {
for (var i=0; i<str.length; i++) {
if ( str.indexOf(str[i]) !== str.lastIndexOf(str[i]) ) {
return false; // repeats
}
}
return true;
}
console.log( charRepeats(example) ); // 'false', because when it hits 'l', the indexOf and lastIndexOf are not the same.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23686 次 |
| 最近记录: |