如何使用Set打印回文词

时间:2017-05-19 10:05:36

标签: java

我正在尝试存储&使用Set打印字符串中的palindrom单词数。请帮帮我。

import java.util.*;
public class PalindromeCount {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a sentence");
        String str = sc.nextLine();
        String words[] = str.replaceAll("," , " ").split("");


        Set set = new HashSet();
        for(String wordL : words)
        {
         // I am retrieving each word in String and sending it to the sb
            StringBuffer sb = new StringBuffer(wordL);
            if(sb.reverse().equals(wordL))// here I am checking whether it is palindrome or not if it is palindrome I am adding to set
            {
                set.add(wordL); 
            }
        }
        System.out.println(set);
    }
}

2 个答案:

答案 0 :(得分:0)

更改后的代码片段修复了您正在犯的一些错误。 split(" ")分隔空格而不是每个字符为空字符串。 需要sb.reverse().toString(),因为StringBuilderStringBuffer不是字符串。

String words[] = str.replaceAll("," , "").split(" ");

Set set = new HashSet();
for(String wordL : words){
    StringBuilder sb = new StringBuilder(wordL);
    if(sb.reverse().toString().equals(wordL)){
        set.add(wordL); 
    }

您还可以使用正则表达式来消除标点符号和额外空格。

//remove everything not in the alphabet
str = str.replaceAll("[^a-zA-Z ]" , " ");
//remove all multiple spaces and replace with a single space
str = str.replaceAll("\\s+", " ").trim();

String words[] = str.split(" ");

答案 1 :(得分:-1)

为您的问题使用此代码。

public static void main(String[] args)
{

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a sentence");
    int st = sc.nextInt();

    Set set = new HashSet();
    int palindrome = st; // copied number into variable
    int reverse = 0;
    while (palindrome != 0)
    {
        int remainder = palindrome % 10;
        reverse = reverse * 10 + remainder;
        palindrome = palindrome / 10;
    }
    if (st == reverse)
    {
        set.add(reverse);
    }

    System.out.println(set);
}