iT邦幫忙

2022 iThome 鐵人賽

DAY 24
0

三種迴文判斷程式碼

  1. 利用while loop處理
import java.util.Scanner;

public class Palindrome {
    public static void main(String[] args) {
        // Create a Scanner
        Scanner input = new Scanner(System.in);

        // Prompt the user to enter a string
        System.out.print("Enter a string: ");
        String s = input.nextLine();
        System.out.println(s + (isPalindrome(s) ? " is" : " is not") + " a Palindrome");
    }
    public static boolean isPalindrome(String s){
        // The index of the first character in the string
        int low = 0;
        // The index of the last character in the string
        int high = s.length() - 1;
        boolean isPalindrome = true;
        while (low < high) {
            if (s.charAt(low) != s.charAt(high)) {
                isPalindrome = false;
                break;
            }
            low++;
            high--;
        }
        return isPalindrome;
    }
}
  1. 利用遞迴方法處理
import java.util.Scanner;

public class Palindrome {
    public static void main(String[] args) {
        // Create a Scanner
        Scanner input = new Scanner(System.in);

        // Prompt the user to enter a string
        System.out.print("Enter a string: ");
        String s = input.nextLine();
        System.out.println(s + (isPalindrome(s) ? " is" : " is not") + " a Palindrome");
    }
    public static boolean isPalindrome(String s) {
        if (s.length() <= 1) {
            return true;
        } else if (s.charAt(0) != s.charAt(s.length() - 1)) {
            return false;
        } else {
            return isPalindrome(s.substring(1, s.length() - 1));
        }
    }
}
  1. 利用遞迴 + 輔助方法(overloading)處理
import java.util.Scanner;

public class Palindrome {
    public static void main(String[] args) {
        // Create a Scanner
        Scanner input = new Scanner(System.in);

        // Prompt the user to enter a string
        System.out.print("Enter a string: ");
        String s = input.nextLine();
        System.out.println(s + (isPalindrome(s) ? " is" : " is not") + " a Palindrome");
    }
    public static boolean isPalindrome(String s) {
        return isPalindrome(s, 0, s.length() - 1);
    }
    // overloading
    private static boolean isPalindrome(String s, int low, int high) {
        if (high <= low) {
            return true;
        } else if (s.charAt(low) != s.charAt(high)) {
            return false;
        } else {
            return isPalindrome(s, low + 1, high - 1);
        }
    }
}

上一篇
Search and Sort
下一篇
來個8D吧
系列文
寫寫歷年職場經歷過的大小事或近期所學習的知識啟發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言