Java在给定字符串中打印最小和最大可能的回文词
在此程序中,我们需要找到在给定字符串中存在的最小和最大回文词。
算法
main()
步骤1: 开始
第2步: DEFINE String string ="Wow you own kayak"
步骤3: 定义 word = " ", smallPalin = " ", bigPalin = " "
步骤4: 定义 String words[]
步骤5: SET temp = 0,count = 0
步骤6: 将字符串转换为小写
步骤7: string = string + " "
步骤8: SET i = 0。直到i < string.length()重复步骤9至步骤11
步骤9: 将字符串分割成单词。
步骤10: IF(string.charAt(i) != ' ') then
word = word + string.charAt(i)
else
words[temp]= word
temp = temp+1 word = " "
步骤11: i = i + 1
步骤12: SET i = 0。直到i < temp 重复步骤13至步骤17
步骤13: IF(isPalindrome(words [i]))然后
count = count + 1
转到步骤14
步骤14: IF(count == 1) smallPalin = bigPalin = words[i]
否则转到步骤15和步骤16
步骤15: 如果 smallPalin的长度大于words[i]的长度,则
smallPalin =words[i]
步骤16: 如果 bigPalin的长度小于words[i]的长度,则
bigPalin =words[i]
步骤17: i = i + 1
步骤18: ,如果IF(count == 0),则打印"No palindrome is present in the given string""
else
打印smallPalin,bigPalin
STEP 19: END
isPalindrome(String a)
步骤1: 开始
步骤2: SET flag= true
步骤3: SET i = 0。重复步骤4到步骤5直到i < a.length()/2
步骤4: IF(a.charAt(i)!=a.charAt(a.length()-i-1) 然后
flag = false
break;
步骤5: i = i + 1
步骤6: RETURN flag
步骤7: END
程序:
import java.io.BufferedReader;
import java.io.FileReader;
public class CountWordFile
{
public static void main(String[] args) throws Exception {
String line;
int count = 0;
//Opens a file in read mode
FileReader file = new FileReader("data.txt ");
BufferedReader br = new BufferedReader(file);
//Gets each line till end of file is reached
while((line = br.readLine()) != null) {
//Splits each line into words
String words[] = line.split("");
//Counts each word
count = count + words.length;
}
System.out.println("Number of words present in given file: " + count);
br.close();
}
}
输出:
Number of words present in given file: 63