Javaで実装された回文文字列を判断します

1.はじめに

プログラムは、lowとhighの2つの変数を使用し、 '文字列sの最初と最後の2つの文字の位置を表します。最初、lowは0で、highはs.length()-1です。これらの2つの位置の文字が一致する場合は、低に1を加算し、高に1を減算します。このプロセスは、(low> = high)になるか、不一致が見つかるまで続きます。
プログラムはブール変数isPalindromeを使用して、文字列sが回文であるかどうかを示します。最初、この変数はtrueに設定されています。不一致が発生すると、isPalindromeはfalseに設定され、ループはbreakステートメントで終了します。

2.コード

package com.zhuo.base.com.zhuo.base;

import java.util.Scanner;

public class Palindrome {
    
    
    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a String: ");
        String s = input.nextLine();
        //字符串中第一个字符的索引
        int low = 0;
        //字符串中最后一个字符的索引
        int high = s.length() - 1;
        boolean isPalindrome = true;
        while (low < high) {
    
    
            if (s.charAt(low) != s.charAt(high)) {
    
    
                isPalindrome = false;
                break;
            }
            low ++;
            high --;
        }
        if (isPalindrome)
            System.out.println(s + " is a palindrome");
        else
            System.out.println(s + " is not a palindrome");
    }
}

3.結果の表示

Enter a String: moon
moon is not a palindrome

Process finished with exit code 0

Enter a String: nonn
nonn is not a palindrome

Process finished with exit code 0

おすすめ

転載: blog.csdn.net/weixin_42768634/article/details/113606864