Check string for palindrome

前端 未结 30 3141
悲哀的现实
悲哀的现实 2020-11-22 02:47

A palindrome is a word, phrase, number or other sequence of units that can be read the same way in either direction.

To check whether a word is a palindrome I get th

30条回答
  •  礼貌的吻别
    2020-11-22 03:21

    And here a complete Java 8 streaming solution. An IntStream provides all indexes til strings half length and then a comparision from the start and from the end is done.

    public static void main(String[] args) {
        for (String testStr : Arrays.asList("testset", "none", "andna", "haah", "habh", "haaah")) {
            System.out.println("testing " + testStr + " is palindrome=" + isPalindrome(testStr));
        }
    }
    
    public static boolean isPalindrome(String str) {
        return IntStream.range(0, str.length() / 2)
                .noneMatch(i -> str.charAt(i) != str.charAt(str.length() - i - 1));
    }
    

    Output is:

    testing testset is palindrome=true
    testing none is palindrome=false
    testing andna is palindrome=true
    testing haah is palindrome=true
    testing habh is palindrome=false
    testing haaah is palindrome=true
    

提交回复
热议问题