编辑代码

class Main {
	public static void main(String[] args) {
       // 台阶问题
        System.out.println("Climb Stairs Recursive: " + climbStairsRecursive(10));
        System.out.println("Climb Stairs Iterative: " + climbStairsIterative(10));

        // 阶乘问题
        System.out.println("Factorial Recursive: " + factorialRecursive(5));
        System.out.println("Factorial Iterative: " + factorialIterative(5));

        // 斐波那契问题
        System.out.println("Fibonacci Recursive: " + fibonacciRecursive(6));
        System.out.println("Fibonacci Iterative: " + fibonacciIterative(6));

        // 回文字符串
        System.out.println("Is Palindrome Recursive: " + isPalindromeRecursive("abba"));
        System.out.println("Is Palindrome Iterative: " + isPalindromeIterative("abba"));
	}
    // 1. 台阶问题
    public static int climbStairsRecursive(int n) {
        if (n <= 1) {
            return 1;
        }
        return climbStairsRecursive(n-1) + climbStairsRecursive(n-2);
    }

    public static int climbStairsIterative(int n) {
        if (n <= 1) {
            return 1;
        }
        int a = 1, b = 1;
        for (int i = 2; i <= n; ++i) {
            int temp = b;
            b = a + b;
            a = temp;
        }
        return b;
    }

    // 2. 阶乘问题
    public static int factorialRecursive(int n) {
        if (n == 0 || n == 1) {
            return 1;
        }
        return n * factorialRecursive(n-1);
    }

    public static int factorialIterative(int n) {
        int result = 1;
        for (int i = 1; i <= n; ++i) {
            result *= i;
        }
        return result;
    }

    // 3. 斐波那契问题
    public static int fibonacciRecursive(int n) {
        if (n <= 1) {
            return n;
        }
        return fibonacciRecursive(n-1) + fibonacciRecursive(n-2);
    }

    public static int fibonacciIterative(int n) {
        if (n <= 1) {
            return n;
        }
        int a = 0, b = 1;
        for (int i = 2; i <= n; ++i) {
            int temp = b;
            b = a + b;
            a = temp;
        }
        return b;
    }

    // 4. 回文字符串
    public static boolean isPalindromeRecursive(String str) {
        if (str.length() <= 1) {
            return true;
        } else if (str.charAt(0) == str.charAt(str.length() - 1)) {
            return isPalindromeRecursive(str.substring(1, str.length() - 1));
        }
        return false;
    }



    public static boolean isPalindromeIterative(String str) {
        int left = 0;
        int right = str.length() - 1;

        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}