华为机试真题~字符串求解

img

昨天刚考的,没做出来,求各位大神给个思路或解题步骤

给两个数组,第一个放字符串 第一个放数字。
如果存在,就找到它的字符串对应的数字数组下标做加法;
或者直接用Map

如下


public static void main(String[] args){
        String[] str = new String[100];
        int[] nmb = new int[100];
        int cnt = 0;
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String s = sc.next();
            String[] st = s.split(",");
            if(st.length == 2){
                int j;
                for(j = 0;j<cnt;j++){
                    if(str[j].equals(st[0]))
                        break;
                }
                if(j==cnt){
                    str[cnt] = st[0];
                    nmb[cnt] = Integer.parseInt(st[1]);
                }else{
                    nmb[j] += Integer.parseInt(st[1]);
                }
            }
        }
        //统计大于10的
        int tt=0;
        for(int i=0;i<cnt;i++){
            if(nmb[i]>10)
                tt++;
        }
        System.out.println(tt);
    }//main end

遍历这个list,定义一个map,list[i]是map结构,按逗号分割,map中没有该key就把它存进map里面,继续遍历下一个,如果key存在,就把当前map中的value更新,最后看下这个map中的value大于10的个数就行


import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Exercise {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        Map<String, String> m = new HashMap<>();

        while (scanner.hasNextLine()) {
            String[] str1 = new String[6];
            for (int i = 0; i < 6; i++) {
                str1[i] = scanner.nextLine();
            }

            for (String str : str1) {
                int i = str.indexOf(",");
                String key = str.substring(0, i);
                String value = str.substring(i + 1);

                if (m.containsKey(key)) {
                    int val = Integer.parseInt(m.get(key)) + Integer.parseInt(value);
                    m.put(key, val + "");
                } else {
                    m.put(key, value);
                }
            }

            int count = 0;
            for (String key11 : m.keySet()) {
                if (Integer.parseInt(m.get(key11)) > 10) {
                    count++;
                }
            }
            System.out.println(count);
        }
    }
}