Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Created November 10, 2017 02:05
Show Gist options
  • Save shailrshah/6571d6b032bebccc05944d0742dcd1d3 to your computer and use it in GitHub Desktop.
Save shailrshah/6571d6b032bebccc05944d0742dcd1d3 to your computer and use it in GitHub Desktop.
Given a sentence delimited by spaces, reverse the sentence.
public String reverseWords(String s) {
String[] a = s.replaceAll("\\s+", " ").split(" ");
int i = 0, j = a.length-1;
while(i < j) {
String temp = a[i];
a[i++] = a[j];
a[j--] = temp;
}
return String.join(" ", a).trim();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment