非哈希map方法,初学者强推,初学者适用版本。
统计一句话中重复单词的个数
https://www.nowcoder.com/practice/2128e598b5a5407195c31175b5b33360?tpId=220&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E8%25AF%25AD%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D220
首先输入一段字符串,然后先去除里面非字母字符,例如,./?';等,可以使用官方代码:
line = line.replaceAll("[^a-zA-Z]", "");
如果你不会正则表达式,也可以使用:
String str = "aaaa bbbb ccccc dd" // 这里的字符串时随机给定的,我们假设给的aaaa bbbb ccccc dd str.replace(',',' '); str.replace('?',' '); // ......... 根据现在能确定的字符来去除。这里不一一列举。
要达到图中这种效果,首先你需要两个数组,一个是字符数组,一个是整形数组,
字符数组用来存放原字符串中的非重复字符,整形数组用来表示对应下标的字符数组中字符的出现次数。如下图
然后遍历原字符数组,使用charAt()来获取字符串对应下标的字符:
String str = "aaaa bbbb ccccc dd"; int i = 0; char ret = str.charAt( i ) // charAt() 返回值为char类型的数据。
然后用遍历得到的字符,一个一个的和字符数组里面的元素进行比较,如果这个遍历得到的字符已经存在于字符数组当中,那么记录他的下标,然后在对应int数组的下标中的元素进行++自增操作。如果不存在那么就直接追加到字符数组中去,由于java整形数组初始化默认为0,这里也可以进行自增。
因为之前使用 ' '空格字符来替换非字母字符,那么在最后打印的时候,只需要跳过空格字符即可
完整代码如下:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextLine()) { // 多组输入 String tem = in.nextLine(); tem = tem.replace(',',' '); tem = tem.replace('?',' '); tem = tem.replace('!',' '); tem = tem.replace('\'',' '); tem = tem.replace('\"',' '); char[] arrChar = new char[100]; int[] arrInt = new int[100]; int size = 0 ; for(int i =0 ; i < tem.length() ; i++){ int flag = -1; for(int j = 0; j<size ; j++){ if( tem.charAt(i) == arrChar[j]){ flag = j; } } if( flag == -1 ){ arrChar[size] = tem.charAt(i); arrInt[size]++; size++; }else{ arrInt[flag]++; } } for(int i = 0; i<size ; i++){ if ( arrChar[i] == ' '){ // 跳过空格字符的统计 continue; } System.out.println(Character.toString( arrChar[i]) + ":"+Integer.toString(arrInt[i])); } } } }