Java教程

Java确定给定的字符串是否是回文

在此程序中,我们需要检查给定字符串是否为回文。
A如果两端都相同,则称该字符串为回文。例如上面的字符串是回文,因为如果我们尝试从后向读取它,则它与向前相同。一种检查方法是遍历字符串直到字符串中间,然后来回比较一个字符。

算法

步骤1: START 步骤2: DEFINE String string ="Kayak" 步骤3: SET标志= true 步骤4: 将字符串转换为小写字母。 步骤5: SET i = 0。直到i将步骤6重复到步骤7 步骤6: IF (string.charAt(i) != string.charAt(string.length()-i-1))
then
SET flag = false
break
步骤7: SET i = i + 1 第8步: 如果IF flag
然后 PRINT" Yes"
else
PRINT" No"
步骤9: END

程序:

public class PalindromeString
{
    public static void main(String[] args) {
        String string = "Kayak";
        boolean flag = true;
        //Converts the given string into lowercase
        string = string.toLowerCase();
        //Iterate the string forward and backward, compare one character at a time
        //till middle of the string is reached
        for(int i = 0; i < string.length()/2; i++){
            if(string.charAt(i) != string.charAt(string.length()-i-1)){
                flag = false;
                break;
            }
        }
        if(flag)
            System.out.println("Given string is palindrome");
        else
            System.out.println("Given string is not a palindrome");
    }
}
输出:
Given string is palindrome
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4