检查句子是否向前和向后都有相同的单词

时间:2017-11-21 18:21:20

标签: java palindrome

我试图检查一个句子是向前和向后是一样的还是一个“句子回文”。句子“你可以笼住燕子,不能你,但你不能吞下笼子,可以吗?”应该返回(True)作为回文。忽略一切不是字母的东西。

我的问题:不确定如何比较单词。这目前适用于检查它们是否是回文的单词,但我需要弄清楚要比较每个单词的内容。

public static boolean isWordPalindrome(String input) {
  Deque<Character> q = new LinkedList<>( );
  Deque<Character> q2 = new LinkedList<>( );

  Character letter;   // One character from the input string
  int mismatches = 0; // Number of spots that mismatched
  int i;              // Index for the input string
  int x;

  for (i = 0; i < input.length( ); i++)
  {
 letter = input.charAt(i); // read next character in the string
     if (letter.toString().equals(',') || letter.toString().equals('"') || letter.toString().equals('?') || letter.toString().equals('!') || letter.toString().equals('.') || letter.toString().equals(' ')) {
         //throwaway.add(letter); //ignore above chars and put in throwaway stack
     }
     if (Character.isLetter(letter)) // if letter put into q's
     {
        q.add(letter);
        q2.addFirst(letter);
     }
  } // end of for loop


  System.out.println("q: " + q);
  System.out.println("q2:" + q2);

  while (!q.isEmpty( ))
  {
     if (!Objects.equals(q.remove(), q2.remove()))
        mismatches++;
  }

2 个答案:

答案 0 :(得分:2)

我将删除所有特殊字符,用空格分割字符串并检查列表是否为“对称”:

private static boolean isSentancePalindrom(String sentence) {
    String[] words = sentence.replaceAll("[^a-zA-Z ]", "").split("\\s+");
    for (int i = 0; i < words.length / 2; ++i) {
        if (!words[i].equalsIgnoreCase(words[words.length - i - 1])) {
            return false;
        }
    }

    return true;
}

答案 1 :(得分:1)

我想出了这个:

   public static boolean checkString(String str) {

    str = str.replaceAll("[,\\?\\.!]+", "").toUpperCase();

    String[] split = str.split(" ");
    String[] reverse = new String[split.length];

    System.arraycopy(split, 0, reverse, 0, split.length);

    List<String> listOfSring = Arrays.asList(split);
    List<String> reversListOfSring = Arrays.asList(reverse);

    Collections.reverse(reversListOfSring);
    return reversListOfSring.equals(listOfSring);   

}

我希望它会有所帮助!