Judge the palindrome string, implemented in java

1. Introduction

The program uses two variables, low and high, and'represents the positions of the two characters at the beginning and the end of the string s. Initially, low is 0 and high is s.length()-1. If the characters in these two positions match, add 1 to low and subtract 1 to high. This process continues until (low>=high), or a mismatch is found.
The program uses a boolean variable isPalindrome to indicate whether the string s is a palindrome. Initially, this variable is set to true. When a mismatch occurs, isPalindrome is set to false and the loop ends with a break statement.

2. Code

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");
    }
}

Three. Results display

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

Guess you like

Origin blog.csdn.net/weixin_42768634/article/details/113606864