I was trying to solve this leet code question 557. Reverse Words in a String III
in this question, I had to reverse the order of characters in each word within a sentence
while still preserving whitespace and initial word order.
eg :
Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
so I wrote this class in my IDEA
and I got this strange output: [C@3fee733d
this is my try:
public class ReveseWordsInString {
public static void main(String[] args) {
String s = "lets get a leet code challanges ";
System.out.println(s);
System.out.println(reverseWords(s));
}
//after knowing the first and the last index of the word
// we call the reverseGivenWord() to reverse that word
public static String reverseWords(String s) {
if (s.length() == 1)
return s;
char[] words = s.toCharArray();
int firstIndexOfTheWord = 0;
int lastIndexOfTheWord;
for (int i = 1; i < s.length(); i++) {
if (words[i] == ' ') {
lastIndexOfTheWord = i - 1;
reverseGivenWord(words, firstIndexOfTheWord, lastIndexOfTheWord);
firstIndexOfTheWord = i + 1;
}
}
return words.toString();
}
//this method reverse a given word
public static void reverseGivenWord(char[] word, int left, int right) {
char temp;
while (left <= right) {
if (word[left] != word[right]) {
temp = word[right];
word[right] = word[left];
word[left] = temp;
}
right--;
left++;
}
}
}
`