标签:练习 uil 包含 count 设计 word void builder let
package com.n;
public class Letter {
private String word;
private int times;
public Letter( ){
}
public Letter(String word,int times2){
this.word=word;
this.times=times2;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public int getTimes() {
return times;
}
public void setTimes(int times) {
this.times = times;
}
}
package com.n;
/*第一题:10个评委评分,除掉最高分和最低分,计算最后选手的平均分。
第二题:
题目描述:请编写程序,从包含大量单词的文本中删除出现次数最少的单词。如果有多个单词都出现最少的次数,则将这些单词都删除。
评分标准:程序输出结果必须正确,内存使用越少越好,程序的执行时间越快越好。
hello world world nihao xyz hello hello nihao
String info = "hello world world nihao xyz hello hello nihao 你好";
1 知道这个字符串里面有多少个单词 hello world nihao xyz
String s[] = info.split(" ");
2 知道每个单词出现的次数
hello 3
world 2
nihao 2
xyz 1
3 info.replaceAll("xyz","");
4 String StringBuilder
*/
public class First {
public static void main(String[] args) {
String s = "hello world world nihao xyz hello hello nihao";
System.out.println("替换之前的字符串是:"+s);
// 一共有多少个单词
String[] ss = s.split(" ");
System.out.println("单词的个数是:" + ss.length);
String[] words = new String[ss.length];// 极端情况,每个单词只出现一次
words[0] = ss[0];
int count = 1;// 记录words数组中有多少个非空元素,即不同的单词个数
for (int i = 1; i < ss.length; i++) {
int j = 0;
for (; j < count; j++) {// 取出words中的每一个单词
if (words[j].equals(ss[i])) {
break;
}
}
if (j==count) {//说明在words中没找到该单词
words[j]=ss[i];
count++;
}
}
System.out.println("不同的单词如下:");
for (int i = 0; i < count; i++) {
System.out.print(words[i]+" ");
}
System.out.println();
Letter[] letters=new Letter[count];
for (int i = 0; i < count; i++) {
int times=0;
int index=0;
while(true){
index=s.indexOf(words[i],index);
if (index==-1) {
break;
}else{
times++;
index=s.indexOf(words[i],index)+words[i].length();
}
}
Letter letter=new Letter(words[i],times);
letters[i]=letter;
}
for (Letter letter : letters) {
System.out.println(letter.getWord()+" "+letter.getTimes());
}
int min=letters[0].getTimes();
for (Letter letter : letters) {
if (letter.getTimes()<min) {
min=letter.getTimes();
}
}
System.out.println("min="+min);
//第一方法:
/* String s1=null;
for (Letter letter : letters) {
if (letter.getTimes()==min) {
s1=s.replaceAll(letter.getWord()+"", "");
}
}
System.out.println("替换完的字符串是:"+s1);
*/
//第二方法:
for (int i=0;i<count;i++) {
if (letters[i].getTimes()==min) {
if (i==(count-1)) {
s=s.replaceAll(letters[i].getWord(),"");
}else{
s=s.replaceAll(letters[i].getWord()+"", "");
}
}
}
System.out.println("替换完的字符串是:"+s);
}
}
运行结果:
标签:练习 uil 包含 count 设计 word void builder let
原文地址:http://www.cnblogs.com/mashuangying2016/p/6549900.html