-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseWordsRecursively.java
More file actions
28 lines (24 loc) · 962 Bytes
/
ReverseWordsRecursively.java
File metadata and controls
28 lines (24 loc) · 962 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.Scanner;
class ReverseWordsRecursively {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a paragraph: ");
String paragraph = scanner.nextLine();
String reversedParagraph = reverseWords(paragraph);
System.out.println("Reversed paragraph: " + reversedParagraph);
}
public static String reverseWords(String paragraph) {
String[] words = paragraph.split("\\s+");
StringBuilder reversedParagraph = new StringBuilder();
for (String word : words) {
reversedParagraph.append(reverseWord(word)).append(" ");
}
return reversedParagraph.toString().trim();
}
public static String reverseWord(String word) {
if (word.length() == 0) {
return "";
}
return word.charAt(word.length() - 1) + reverseWord(word.substring(0, word.length() - 1));
}
}