java - 1772 of Caribbean online judge giving a time limit exceeded error. please help me find why is my algorithm taking so long -


so trying solve problem 1772 of caribbean online judge web page http://coj.uci.cu/24h/problem.xhtml?abb=1772, problem asks find if substring of bigger string contains @ least 1 palindrome inside it:

e.g. analyzing sub-strings taken following string: "baraabarbabartaarabcde"

"bara" contains palindrome "ara"

"abar" contains palindrome "aba"

"babar" contains palindrome "babar"

"taar" contains palindrome "aa"

"abcde" not contains palindrome.

etc etc etc...

i believe approach fast because iterating strings starting @ first char , @ last char @ same time, advancing towards center of string looking following patterns: "aa" "aba" whenever find pattern can substring given contains palindrome inside it. problem algorithm taking long time can't spot problem on it. please me find lost on one. here algorithm

public static boolean haspalindromeinside(string str) {     int midpoint=(int) math.ceil((float)str.length()/2.0);     int k = str.length()-1;      for(int = 0; < midpoint;i++)     {         char letterleft = str.charat(i);         char secondletterleft=str.charat(i+1);         char letterright = str.charat(k);         char secondletterright =  str.charat(k-1);          if((i+2)<str.length())         {             char thirdletterleft=str.charat(i+2);             char thirdletterright=str.charat(k-2);               if(letterleft == thirdletterleft || letterright == thirdletterright)             {                 return true;             }          }           if(letterleft == secondletterleft || letterright==secondletterright)         {             return true;         }      k--;     }     return false; } } 

i have removed code grabs input strings , intervals of sub-strings, using string.substring() substrings , don't think causing problem. if need code please let me know. thanks!

i think can solve in o(1) time per query given o(n) preprocessing find locations of 2 , 3 character palindromes. (any plaindrome have 2 character plaindrome @ centre, while odd have 3 character 1 suffices check 2 , 3.)

for example,

given string baraabarbabartaarabcde, first compute array indicating locations of 2 character palindromes:

baraabarbabartaarabcde 000100000000001000000- 

then compute cumulative sum of array:

baraabarbabartaarabcde 000100000000001000000- 000111111111112222222- 

by doing subtraction can work out whether there 2 character palindromes in query range.

similarly 3 character plaindromes:

baraabarbabartaarabcde  string 01001000100000010000--  indicator 01112222333333344444--  cumulative 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -