Question: Given a String S, reverse the string without reversing its individual words. Words are separated by dots.
Example 1:
Input:
S = i.like.this.program.very.much
Output: much.very.program.this.like.i
Explanation: After reversing the whole
string(not individual words), the input
string becomes
much.very.program.this.like.i
Solution 1: Brute Force
Split the string with dots and store each word in any array. Iterate the words array in reverse and append each word in the string followed by a space as seprartor.
Assumption here is that there is single dot separating the words.
Input:
class Solution { String reverseWords(String S) { final String[] arr = S.split("\\."); String output = ""; final int len = arr.length; if (len == 1) { return arr[0]; } else if (len == 0) { return output; } else { for (int i = len - 1; i > 0; i--) { output = output + arr[i] + "."; } output = output + arr[0] return output; } }}Complexity of the solution is O(n) because the split function iterates the whole string to find the dot.
Comments
Post a Comment