How can I print the palindrome words in a sentence? If I input "Madam Arora teaches math", it should print "Madam Arora"

huangapple go评论71阅读模式
英文:

How can I print the palindrome words in a sentence? If I input "Madam Arora teaches math", it should print "Madam Arora"

问题

import java.util.Stack;
import java.util.Queue;
import java.util.LinkedList;

class Palindrome {

    // Function to check if a word is palindrome
    static boolean checkPalin(String word) {
        int n = word.length();
        word = word.toLowerCase();
        for (int i = 0; i < n; i++, n--)
            if (word.charAt(i) != word.charAt(n - 1))
                return false;
        return true;
    }

    // Function to check if a word is palindrome using stacks and queues
    static boolean checkPalinUsingStackAndQueue(String word) {
        int n = word.length();
        word = word.toLowerCase();

        Stack<Character> stack = new Stack<>();
        Queue<Character> queue = new LinkedList<>();

        for (int i = 0; i < n; i++) {
            char ch = word.charAt(i);
            if (Character.isLetter(ch)) {
                stack.push(ch);
                queue.add(ch);
            }
        }

        while (!stack.isEmpty()) {
            if (!stack.pop().equals(queue.remove())) {
                return false;
            }
        }

        return true;
    }

    // Function to count palindrome words
    static int countPalin(String str) {
        str = str + " ";

        String word = "";
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);

            if (Character.isLetter(ch)) {
                word = word + ch;
            } else {
                if (!word.isEmpty() && checkPalinUsingStackAndQueue(word)) {
                    count++;
                }
                word = "";
            }
        }

        return count;
    }

    // Driver code
    public static void main(String args[]) {
        System.out.println(countPalin("Madam " + "Arora teaches malayalam"));
        System.out.println(countPalin("Nitin " + "speaks malayalam"));
    }
}
英文:
class Palindrome { 
      
    // Function to check if a word is 
    // palindrome 
    static boolean checkPalin(String word) 
    { 
        int n = word.length(); 
        word = word.toLowerCase(); 
        for (int i=0; i&lt;n; i++,n--) 
           if (word.charAt(i) != word.charAt(n - 1)) 
              return false;        
        return true; 
    } 
      
    // Function to count palindrome words 
    static int countPalin(String str) 
    {         
        // to check last word for palindrome 
        str = str + &quot; &quot;; 
          
        // to store each word 
        String word = &quot;&quot;; 
        int count = 0; 
        for (int i = 0; i &lt; str.length(); i++) 
        { 
            char ch = str.charAt(i); 
              
            // extracting each word 
            if (ch != &#39; &#39;) 
                word = word + ch; 
            else { 
                if (checkPalin(word)) 
                    count++; 
                word = &quot;&quot;; 
            } 
        } 
          
        return count; 
    } 
      
    // Driver code 
    public static void main(String args[]) 
    { 
        System.out.println(countPalin(&quot;Madam &quot;
                  + &quot;Arora teaches malayalam&quot;)); 
                    
        System.out.println(countPalin(&quot;Nitin &quot;
                        + &quot;speaks malayalam&quot;)); 
    }
}

I only know how to count the number. How can I run through a loop and check every word if it is a palindrome? Can you help me with a method that checks a word and a method that checks a sentence if there are palindrome words? I must use Stacks and Queues. I have done the push, add, remove, dequeue, but I can't check if the input is a sentence.

答案1

得分: 0

// C#程序:统计句子中回文单词的数量
using System;

class Palindrome
{

    // 函数:检查单词是否为回文
    public static bool checkPalin(string word)
    {
        int n = word.Length;
        word = word.ToLower();
        for (int i = 0; i < n; i++, n--)
        {
            if (word[i] != word[n - 1])
            {
                return false;
            }
        }
        return true;
    }

    // 函数:统计回文单词数量
    public static string countPalin(string str)
    {
        // 用于检查最后一个单词是否为回文
        str = str + " ";

        // 存储每个单词
        string word = "";
        string Print_Result = "";
        int count = 0;
        for (int i = 0; i < str.Length; i++)
        {
            char ch = str[i];

            // 提取每个单词
            if (ch != ' ')
            {
                word = word + ch;
            }
            else
            {
                if (checkPalin(word))
                {
                    if (Print_Result == "")
                    {
                        Print_Result = word;
                    }
                    else
                    {
                        Print_Result = Print_Result + " " + word;
                    }
                }
                word = "";
            }
        }

        return Print_Result;
    }

    // 主程序
    public static void Main(string[] args)
    {
        Console.WriteLine(countPalin("Madam " +
                "Arora teaches math"));
    }
}
英文:
// C# program to count number of 
// palindrome words in a sentence 
using System; 
class Palindrome 
{ 
// Function to check if a word is 
// palindrome 
public static bool checkPalin(string word) 
{ 
int n = word.Length; 
word = word.ToLower(); 
for (int i = 0; i &lt; n; i++,n--) 
{ 
if (word[i] != word[n - 1]) 
{ 
return false; 
} 
} 
return true; 
} 
// Function to count palindrome words 
public static int countPalin(string str) 
{ 
// to check last word for palindrome 
str = str + &quot; &quot;; 
// to store each word 
string word = &quot;&quot;; 
string Print_Result = &quot;&quot;;
int count = 0; 
for (int i = 0; i &lt; str.Length; i++) 
{ 
char ch = str[i]; 
// extracting each word 
if (ch != &#39; &#39;) 
{ 
word = word + ch; 
} 
else
{ 
if (checkPalin(word)) 
{ 
if (Print_Result == &quot;&quot;)
{
Print_Result =  word;
}else
{
Print_Result = Print_Result + word;
} 
} 
word = &quot;&quot;; 
} 
} 
return Print_Result; 
} 
// Driver code 
public static void Main(string[] args) 
{ 
Console.WriteLine(countPalin(&quot;Madam &quot; + 
&quot;Arora teaches math&quot;)); 
} 
} 

答案2

得分: 0

你只需要更改这部分内容:

if (checkPalin(word)) 
{ 
     OutPut =  OutPut + word;
}

在循环结束后返回 OutPut。

英文:

You need to change only this part

if (checkPalin(word)) 
{ 
OutPut =  OutPut + word;
}

after for loop return OutPut.

答案3

得分: 0

你可以实现一个方法,在使用String.split将输入字符串拆分后,返回一个回文单词列表。

对于这样的任务,使用Java 8的Stream API非常方便(使用filtercollect操作):

import java.util.*;
import java.util.stream.*;

class Palindrome {
// ...

    public static List<String> findPalindromes(String str) {
        if (null == str || str.isEmpty()) {
            return Collections.emptyList();
        }
        return Arrays.stream(str.split("\\s+")) // 按空格拆分为“单词”
                     .filter(Palindrome::checkPalin) // 保留回文单词
                     .collect(Collectors.toList());  // 从流中获取列表
    }

    // 然后,countPalin() 可以重构为
    public static int countPalin(String str) {
        return findPalindromes(str).size();
    }
}

测试部分:

public static void main(String... args) {
    String[] data = { null, "", "None",
                "Madam Arora teaches malayalam",
                "Nitin speaks malayalam"
    };

    for (String str : data) {
        List<String> palindromes = findPalindromes(str);
        if (palindromes.isEmpty()) {
            System.out.printf("在 \"%s\" 中未找到回文单词%n", str);
        } else {
            System.out.printf("在 \"%s\" 中找到回文单词:%s%n", str, palindromes);
        }
    }
}

输出:

在 "null" 中未找到回文单词
在 "" 中未找到回文单词
在 "None" 中未找到回文单词
在 "Madam Arora teaches malayalam" 中找到回文单词:[Madam, Arora, malayalam]
在 "Nitin speaks malayalam" 中找到回文单词:[Nitin, malayalam]
英文:

You could implement a method to return a list of palindrome words after splitting the input string with String.split.

It is convenient to use Java 8 Stream API for such tasks (filter and collect):

import java.util.*;
import java.util.stream.*;

class Palindrome {
// ...

    public static List&lt;String&gt; findPalindromes(String str) {
        if (null == str || str.isEmpty()) {
            return Collections.emptyList();
        }
        return Arrays.stream(str.split(&quot;\\s+&quot;)) // split into &quot;words&quot; separated with whitespaces
                     .filter(Palindrome::checkPalin) // keep the palindrome words
                     .collect(Collectors.toList());  // get the list from stream
    }

    // then countPalin() may be refactored as
    public static countPalin(String str) {
        return findPalindromes(str).size();
    }
}

Test

public static void main(String... args) {
    String[] data = { null, &quot;&quot;, &quot;None&quot;,
                &quot;Madam Arora teaches malayalam&quot;,
                &quot;Nitin speaks malayalam&quot;
    };

    for (String str : data) {
        List&lt;String&gt; palindromes = findPalindromes(str);
        if (palindromes.isEmpty()) {
            System.out.printf(&quot;No palindromes found in \&quot;%s\&quot;%n&quot;, str);
        } else {
            System.out.printf(&quot;\&quot;%s\&quot; palindromes found in \&quot;%s\&quot;%n&quot;, palindromes, str);
        }
    }
}

Output:

No palindromes found in &quot;null&quot;
No palindromes found in &quot;&quot;
No palindromes found in &quot;None&quot;
&quot;[Madam, Arora, malayalam]&quot; palindromes found in &quot;Madam Arora teaches malayalam&quot;
&quot;[Nitin, malayalam]&quot; palindromes found in &quot;Nitin speaks malayalam&quot;

huangapple
  • 本文由 发表于 2020年9月25日 16:38:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/64060683.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定