# Timed Out!?

Printable View

• 08-24-2011, 08:12 PM
HearT.Hunt3r
Timed Out!?
this Is question: Given a string and a non-empty word string, return a version of the original String where all chars have been replaced by pluses ("+"), except for appearances of the word string which are preserved unchanged.

plusOut("12xy34", "xy") → "++xy++"
plusOut("12xy34", "1") → "1+++++"
plusOut("12xy34xyabcxy", "xy") → "++xy++xy+++xy"

why my code give Timed Out?
Code:

```        public String plusOut(String str, String word) {                 int v=0;                 String res = "";                 for(int i=0;i<str.length();i++){                         v = str.indexOf(word, i);                         for(int z=i;z<v;z++){                                 res+="+";                                }                         res += word;                                i += v-1;                 }         return res;         }```
• 08-24-2011, 08:17 PM
Norm
What values does the i variable have as the loop is executed? And the v and z variables.
Print them out to see.
• 08-24-2011, 11:54 PM
HearT.Hunt3r
finally i could solved it!
Code:

```public String plusOut(String str, String word) {                 int v=0;                 String res = "";                 for(int i=0;i<str.length();i++){                         v = str.indexOf(word, i);                         if(str.indexOf(word, i)<0){                                 for(int z=i;z<=str.length();z++){                                         res+="+";                                        }                                 break;                         }                         for(int z=i;z<v;z++){                                 res+="+";                                        }                         res += word;                                i = v-1+word.length();                 }         return res;         }```
• 08-24-2011, 11:55 PM
HearT.Hunt3r
Quote:

Originally Posted by Norm
What values does the i variable have as the loop is executed? And the v and z variables.
Print them out to see.

value of v was -1 and i got that it must be fixed ... thx.