java simple palindrome algorithm

Algorithm requires

Write a program to determine whether a string is "palindrome." Palindrome sequence: character string coincides with a front to rear from the back (centrosymmetric).

Algorithm thinking

First, the string around two aliquots, followed symmetrical characters are the same for each comparison

Code

import java.util.Scanner;

public class Palindrome {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (!sc.hasNext("###")) {
            String data = sc.next();
            if (isPalin(data)) {
                System.out.println("yes");
            } else {
                System.out.println("no");
            }
        }
        sc.close();
    }

    public static boolean isPalin(String data) {
        int len = data.length();
        for (int i = 0; i < len/2; i++) {
            if (data.charAt(i) != data.charAt(len-1-i)) {
                return false;
            }
        }
        return true;
    }

}

Test case

abc
no
qwq
yes
abcdcba
yes

tips

1, equals and ==

== operator execution rules

  • If the basic data types of variables, their value is more
  • If it is a reference type variable, then compare objects they point to address

equals method execution rules

  • It equals the original method, the address comparison reference type variable points of the object
  • String, Date, etc. based on the equals method has been rewritten at this time compares the contents of the object pointed to

ps: equals method is a method in the base class Object, to compare whether two object references are equal, i.e., whether the same object

Inquiry: Talking in Java equals and == https://www.cnblogs.com/dolphin0520/p/3592500.html

2, sc.hasNext () implement multiple sets of input

!sc.hasNext("###")  // 匹配 ### 返回true,然后取非运算。即以 ### 作为停止输入的命令

hasNext () and next () effect in fact is the same, the system will wait for the next input character, but returns a different value, hasNext () returns true, next () returns the character entered. If hasNext (returns true) when the next parameter is the character and the parameter value will match.

Inquiry: hasNext Scanner's () method https://blog.csdn.net/gao_zhennan/article/details/80562548

Guess you like

Origin www.cnblogs.com/lanselove/p/10974550.html