I have written a coding challenge. The requirement of the challenge is reversing the particular words in a sentence => still keep the oder the of the words in the sentence but reverse the characters of the word.
The input sample is something like this: RemoteIo is awesome
-Candiates pass interview
-best candiates are selected
.
The sample output of the input above:
oIetomeR si emosewa
setaidnaC ssap weivretni
tseb setaidnac era detceles
As you can see the input sentences are separated by the -
character so that mean we have 3 sentences in the example above and the sentence just able to contain anphabet characters and blank space only (one blank space between two words)
So my question is how can I optimize the below code and there is any theory/principle about Code Optimization. My code implementation in Java:
public class Test1 {
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
// Put sentences to a String array.
String[] data = input.split("-");
// Loop throw sentence array
for(int i = 0; i < data.length; i++) {
// Put the words from the sentence to a String array.
String[] words = data[i].split(" ");
// Loop throw the word array
for(int w = 0; w < words.length; w++) {
// Revert the characters of each word
for (int j = words[w].length() - 1; j >=0; j--) {
if (j != 0) {
System.out.print(words[w].charAt(j));
} else {
System.out.print(words[w].charAt(j) + " ");
}
}
if ( w == words.length -1) {
System.out.println();
}
}
}
}
}