Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java กลับลำดับประโยคด้วย Recursion (Reverse String)


ในบทความนี้ เราจะทำความเข้าใจวิธี กลับลำดับสตริง/ประโยค (Reverse String) ด้วย Recursion

หลักการ: reverse(str) = reverse(str.substring(1)) + str.charAt(0) โดย Base Case: สตริงว่างคืนค่าสตริงว่าง

ตัวอย่าง Input และ Output

Input:

Enter the sentence : Have a nice evening

Output:

The reversed input is: gnineve ecin a evaH

อัลกอริธึม

ขั้นตอนที่ 1 - เริ่มต้น
ขั้นตอนที่ 2 - ประกาศตัวแปร String my_input, my_result
ขั้นตอนที่ 3 - อ่านค่าจากผู้ใช้ หรือกำหนดค่าเริ่มต้น
ขั้นตอนที่ 4 - สร้างฟังก์ชัน reverseString แบบ recursive รับสตริง คืนสตริงที่กลับแล้ว
ขั้นตอนที่ 5 - เรียกฟังก์ชันซ้ำจนกว่าสตริงจะว่าง
ขั้นตอนที่ 6 - เรียกฟังก์ชันและเก็บผลลัพธ์
ขั้นตอนที่ 7 - แสดงผลลัพธ์
ขั้นตอนที่ 8 - หยุด

ตัวอย่างที่ 1: รับค่าจากผู้ใช้

import java.util.Scanner;
public class Reverse {
    public static void main(String[] args) {
        String my_input, my_result;
        System.out.println("Required packages have been imported");
        Scanner my_scanner = new Scanner(System.in);
        System.out.println("A reader object has been defined");
        System.out.print("Enter the sentence : ");
        my_input = my_scanner.nextLine();
        my_result = reverseString(my_input);
        System.out.println("The reversed input is: " + my_result);
    }
    public static String reverseString(String my_input) {
        if (my_input.isEmpty())
            return my_input;
        return reverseString(my_input.substring(1)) + my_input.charAt(0);
    }
}

Output

Required packages have been imported
A reader object has been defined
Enter the sentence : Have a nice evening
The reversed input is: gnineve ecin a evaH

ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า

public class Reverse {
    public static void main(String[] args) {
        String my_input, my_result;
        my_input = "Have a nice evening";
        System.out.println("The string is defined as :" + my_input);
        my_result = reverseString(my_input);
        System.out.println("The reversed input is: " + my_result);
    }
    public static String reverseString(String my_input) {
        if (my_input.isEmpty())
            return my_input;
        return reverseString(my_input.substring(1)) + my_input.charAt(0);
    }
}

Output

The string is defined as :Have a nice evening
The reversed input is: gnineve ecin a evaH