There's a simple string manipulation problem where you are required to reverse the words of each line: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=121&page=show_problem&problem=424
So:
I love you.
You love me.
We're a happy family.
Would become:
I evol .uoy
uoY evol .em
er'eW a yppah .ylimaf
Now, I've written a simple java solution which looks something like:
BufferedReader file = new BufferedReader(new InputStreamReader(System.in));
String s;
while((s=file.readLine())!=null){
String[] sr = s.split(" ");
for(int i = 0; i<sr.length; i++)
System.out.print(new StringBuffer(sr[i]).reverse() + (i==sr.length-1?"\n":" "));
}
Because I am trying to learn c++, I've also tried writing a c++ solution which looks like:
string s;
while(getline(cin, s)){
string tmp = "";
for(int i = 0; i<=s.length(); i++)
if( i==s.length() || s[i] == ' '){
for(int j = tmp.length(); j>=0; j--)
cout << tmp[j];
if( i == s.length()) cout << endl;
else cout << " ";
tmp = "";
}else
tmp += s[i];
}
My questions are:
- The c++ solution returns "wrong answer", whereas the java one is accepted, why?
- What improvements, if any, can be made to the c++ solution?