华为坑爹的typedef

华为笔试第三题

题目大意是说通过解析typedef语句定义的代码段来获取某一个变量的原始定义。例子如下:
输入为:typedef int INT; typedef INT** INTP;INTP,
输出为:int * *

import java.util.*;

public class Huawei {
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        String re = scanner.next();
        String[] strings = s.split(";");
        Map map = new HashMap<>();
        String key = "";
        String val = "";
        for (String s1: strings){
            String[] strings2 = s1.split(" ");
            List stringList = new ArrayList();
            for(String s2: strings2){
                if (!s2.equals("")) {
                    stringList.add(s2);
                }
            }
            String[] strings1 = (String[]) stringList.toArray(new String[(stringList.size())]);
            String s2 = strings1[1];
            int start = 0, end = s2.length();
            for(int i = 0; i < s2.length(); i++){
                if(s2.charAt(i) == '&'|| s2.charAt(i) == '*'){
                    start++;
                }else {
                    break;
                }
            }
            for(int i = 0; i < s2.length(); i++){
                if(s2.charAt(s2.length() -1 - i) == '&'|| s2.charAt(s2.length() -1 - i) == '*'){
                    end--;
                }else {
                    break;
                }
            }
            if(map.containsKey(s2.substring(start, end))){
                map.put(strings1[2], s2.substring(0, start) + map.get(s2.substring(start, end)) + s2.substring(end));
            }else{
                map.put(strings1[2], s2);
            }
        }
        String s1 = map.get(re);
        String result = map.get(re).replace("*", " * ").replace("&", " & ");

        String[] res = result.split(" ");
        List stringList = new ArrayList<>();
        for (String s2: res){
            if(!s2.equals("")){
                stringList.add(s2);
            }
        }
        result = String.join(" ", stringList);
        System.out.println(result);
    }
}

通过率48多。
最后通过讨论发现只考虑了*指针的只有20多,好吧我们肯定少了<>[]()等。
与其这样不如直接提取[a-zA-Z_0-9]的变量名,然后替换。

你可能感兴趣的:(华为坑爹的typedef)