javascriptrecursionrepeat

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?

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;
}

Many thanks in advance!


Solution

  • (A recursive solution can be found at the end of this answer)

    You could simply use the builtin javascript Array functions some MDN some reference

     var text = "test".split("");
     text.some(function(v,i,a){
       return a.lastIndexOf(v)!=i;
     });
    

    callback parameters:
    v ... current value of the iteration
    i ... current index of the iteration
    a ... array being iterated

    .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. (it doesn't loop through the whole array, which is good for performance)

    Details to the some function here in the documentation

    Here some tests, with several different strings:

    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+

    If you will want recursion.

    Update for recursion:

    //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+