Skip to content

Instantly share code, notes, and snippets.

@motiooon
Created January 13, 2014 21:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save motiooon/8408927 to your computer and use it in GitHub Desktop.
Save motiooon/8408927 to your computer and use it in GitHub Desktop.
O(n^2) String computation to find reverse words
function reverse_word(w){
return w.split("").reverse().join("");
}
// O(n^2) Implementation
function hasreverse(string){
var s_length = string.length;
var words_reversed=[];
if(s_length < 5) {
return -1;
}else{
for (var i = 2; i < s_length; i++){
var left_characters = string.substr(0, i);
var reverse_left_characters = reverse_word(left_characters);
var right_characters = string.substr(i + 1, s_length);
var word_out = '';
var index = 0;
for(var j = 0; j < reverse_left_characters.length; j++){
if(left_characters[j] && right_characters[j]){
if(reverse_left_characters[j] === right_characters[j]){
word_out += reverse_left_characters[j];
index=i;
}else{
break;
}
}
}
if(word_out.length>2){
words_reversed.push({
word: word_out,
at_index: index
})
}
}
}
return words_reversed;
}
console.log(hasreverse("oracicarlrenogabgyioiygiuduliter")); //should output [{word:"car", at_index:4}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment