Created
January 13, 2014 21:57
-
-
Save motiooon/8408927 to your computer and use it in GitHub Desktop.
O(n^2) String computation to find reverse words
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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