Skip to content

Instantly share code, notes, and snippets.

@motiooon
Last active January 3, 2016 06:59
Show Gist options
  • Save motiooon/8426785 to your computer and use it in GitHub Desktop.
Save motiooon/8426785 to your computer and use it in GitHub Desktop.
Find reversed words in a string. O(n) this time.
var string = "qwertyuiopasdfghjleirbaglgabrielmnbvcdrgythacnakancajuilsre";
function find_reverses(str){
var j = 0;
var potential_reverses = [];
while(j < string.length){
if(string[j] === string[j+2]){
potential_reverses.push({letter:string[j], index: j+2});
}
j++;
}
var word = "";
var reversed_words = [];
for(var i = 0; i<potential_reverses.length; i++){
word += potential_reverses[i].letter;
var j = potential_reverses[i].index+1;
var iteration_step = 2;
while(j < string.length){
if(string[j-iteration_step-2] === string[j]){
word+=string[j];
iteration_step+=2;
j++;
}else{
break;
}
}
if(word.length>1){
reversed_words.push({
word: word,
index:potential_reverses[i].index + 2
});
};
word="";
}
return reversed_words;
}
console.log(find_reverses(string));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment