检查字符串Javascript中的重复字符 [英] Check for repeated characters in a string Javascript
问题描述
我想知道是否有办法在不使用双循环的情况下检查字符串中的重复字符。这可以通过递归来完成吗?
I was wondering if there is a way to check for repeated characters in a string without using double loop. Can this be done with recursion?
使用双循环的代码示例(如果字符串中有重复的字符,则返回true或false):
An example of the code using double loop (return true or false based on if there are repeated characters in a string):
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;
}
非常感谢提前!
推荐答案
(在此答案的最后可以找到递归解决方案。)
(A recursive solution can be found at the end, of this answer.)
您可以使用javascript内置数组函数 some MDN some reference
You could use javascript builtin Array functions some MDN some reference
var text = "test".split("");
text.some(function(v,i,a){
return a.lastIndexOf(v)!=i;
});
回调参数:
v 迭代的当前值
i 当前迭代索引
a 当前数组
callback parameters:
v current value of the iteration
i current index of the iteration
a current array
.split()从字符串创建数组
.some(function(v,i,a){...})通过一个数组,直到函数返回true
,并立即结束。 (如果之前找到匹配项,则不会遍历整个数组)
.split("") create an array from a string
.some(function(v,i,a){ ... }) goes through an array until the function returns true
, and ends than right away. (doesn't loop through the whole array, if it finds an match earlier)
可以找到某些功能的详细信息 here
Details to the some function can be found here
测试,包含多个字符串:
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+
如果需要递归。
递归更新:
//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+
这篇关于检查字符串Javascript中的重复字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!