[英]how to count the number of words of the same(PALINDROME) in java
我是Java新手。 我想編寫代碼以使用Java計算段落中回文詞的數量。
假設是:用戶可以輸入一個包含盡可能多的句子的段落。 每個單詞之間用空格隔開,每個句子之間用句點隔開。單詞之前或之后的標點符號將被忽略,而單詞內部的標點符號將被計數。
輸入樣本: Otto goes to school. Otto sees a lot of animals at the pets store.
Otto goes to school. Otto sees a lot of animals at the pets store.
樣本輸出: Otto = 2 a = 1 Sees = 1
將文件讀入程序,在每個空格處拆分條目,然后將其輸入到arraylist中。 然后,將回文算法應用於數組列表中的每個值,並跟蹤作為回文的單詞及其出現(例如2D數組或具有同時包含兩個值的對象的數組列表)。
完成這些步驟后,您應該已經准備就緒。 一旦您展示了自己的嘗試,可能會提供更多具體的幫助。
在Java中使用Collections將減少編程工作
算法:
將段落讀取為String變量
使用將令牌作為''(空格)的StringTokenizer
分割字符串,並將每個單詞添加到ArrayList中(設置將不允許重復)
編寫一個根據給定的String是否為回文符返回布爾值(TRUE / FALSE)的方法。
定義一個Map,以保存回文字符串的值及其重復次數。
如果是,則將字符串添加到Map,並將鍵作為回文字符串,將值添加為次數,否則不要將字符串添加到Map
重復相同的邏輯,直到所有單詞都完成為止
樣例代碼:
`公共類StringPalindromeCalculator {
private Map<String, int> wordsMap = new HashMap<>();
private List<String> wordsList = new ArrayLiat<>();
private boolean isPalindrome(String inputString) {
// write String palindrome logic here
}
public Map<String, int> findPalindromeWords(String completeString) {
StringTokenizer wordTokenizer = new StringTokenizer(completeString, ' ');
while(wordTokenizer.hasMoreTokens()) {
wordsList.add(wordTokenizer.nextToken());
}
for(String word : wordsList) {
if(isPalindrome(word)) {
if(wordsMap.containsKey(word)) {
// increment the value of word
}
} else {
// put the word into Map and return the map value
}
}
return wordsMap;
}
}`
希望這可以幫助 :)
公共課回文{
int count = 0;
public static void main(String[] args) {
String a = "malayalammadyoydaraarasdasdkfjasdsjhtj";
Palindrome palindrome = new Palindrome();
palindrome.countPalin(a);
}
private int countPalin(String str) {
for (int i = 0; i < str.length() - 1; i++) {
char start = str.charAt(i);
String st = "";
st += start;
for (int j = i + 1; j < str.length(); j++) {
st += str.charAt(j);
StringBuffer rev = new StringBuffer(st).reverse();
if (st.equals(rev.toString()) && st.length() > 1) {
System.out.println(st.toString());
count++;
}
}
st = "";
}
System.out.println("Total Count : " + count);
return count;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.