忽略词缀检查器的大小写[重复]

问题描述 投票:0回答:1

我是一名CS初学者,我正在为一个类制作一个词缀检查器,如果不是主方法中需要使用Uppercasing,这个方法是完全可以使用的,我怎么能让我的isPalindromeRecursive方法忽略字符串的大小写呢?我怎么能让我的isPalindromeRecursive方法忽略字符串的大小写?

我需要想办法做一个不区分大小写的方法。另外,我必须同时拥有isPalindromeRecursive和isPalindromeIterative方法,但我不明白其中的区别,如果有人能解释一下。

public class PalindromeDetector {

    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);

        int count = 2;
        for(int i = 0; i < count; i++ ) {

            System.out.println("Enter a name.");
            String name = keyboard.nextLine();

            // I wanted to experiment with the new String tools we learned so my capitalization is strange.
            String cap = name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
            System.out.println(cap);

            if(isPalindromeRecursive(cap))
                System.out.println(cap + " is a palindrome.");
            else
                System.out.println(cap + " is not a palindrome.");

            count++;
        }

    }

    public static boolean isPalindromeRecursive(String s) {
            if(s.length()==0 || s.length() ==1) {
                return true;
            }
            if(s.charAt(0) == s.charAt(s.length()-1)) {
                return isPalindromeRecursive(s.substring(1, s.length()-1));
            }
                return false;
    }

}
java palindrome case-sensitive case-insensitive
1个回答
0
投票

你可以看看使用 Character.toUpperCase() 比较法 chars 以一种不区分大小写的方式。

你还创建了大量的String对象,但这并不是真正必要的。

把这两者放在一起,你就有了这样的东西。

public static boolean isPalindromeRecursive(String s, int front, int back) 
{
  if(front >= back) {
      return true;
  }

  if(Character.toUpperCase(s.charAt(front)) == Character.toUpperCase(s.charAt(back))) {
      return isPalindromeRecursive(s, front+1, back-1);
  }
  return false;
}

你可以通过调用

for(String s : new String[] {"", "a", "ab", "aa", "aA", "aba", "abA", "abc"})
    System.out.format("%s:%b%n", s, isPalindromeRecursive(s, 0, s.length()-1));

Output:

:true
a:true
ab:false
aa:true
aA:true
aba:true
abA:true
abc:false
© www.soinside.com 2019 - 2024. All rights reserved.