使用递归反转句子的Java程序
句子是由一些定界符分隔的字符序列。此字符序列从第 0 个索引开始,最后一个索引位于 len(字符串)-1。通过反转字符串,我们交换从第 0 个索引开始的字符并将它们从末尾放置。第一个字符变成最后一个,第二个变成倒数第二个,依此类推。
例子:
Input : GeeksforGeeks
Output: skeegrofskeeG
Input : Alice
Output: ecilA
方法:
- 检查字符串是否为空,如果字符串为空则返回null。
- 如果字符串为空,则返回空字符串。
- 否则返回字符串的子字符串部分从索引 1 到字符串长度与字符串的第一个字符的连接。例如 return substring(1)+str.charAt(0);对于字符串“Mayur”返回的字符串将是“ayur”+“M”。
下面是上述方法的实现:
Java
// Java Program to Reverse a Sentence Using Recursion
import java.io.*;
public class GFG {
public static String reverse_sentence(String str)
{
// check if str is empty
if (str.isEmpty())
// return the string
return str;
else {
// extract the character at 0th index, that is
// the character at beginning
char ch = str.charAt(0);
// append character extracted at the end
// and pass the remaining string to the function
return reverse_sentence(str.substring(1)) + ch;
}
}
public static void main(String[] args)
{
// specify the string to reverse
String str = "Geeksforgeeks";
// call the method to reverse sentence
String rev_str = reverse_sentence(str);
// print the reversed sentence
System.out.println(
"Sentence in reversed form is : " + rev_str);
// creating another string with numbers
// and special characters
String str2 = "Alice";
String rev_str2 = reverse_sentence(str2);
// print the reversed sentence
System.out.println(
"Sentence in reversed form is : " + rev_str2);
}
}
输出
Sentence in reversed form is : skeegrofskeeG
Sentence in reversed form is : ecilA
时间复杂度: O(N),其中 N 是字符串的长度。