Java Pattern & HashMap


  • 0
    L
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class Solution {
        public List<List<String>> findDuplicate(String[] paths) {
            Pattern p = Pattern.compile("(.*\\.txt)\\((.*)\\)");
            Map<String,List<String>> map = new HashMap<>();
            for(String str:paths){
                String[] strings = str.split(" ");
                for(int i=0;i<strings.length;i++){
                    if(i == 0){
                        continue;
                    }else {
                        Matcher m = p.matcher(strings[i]);
                        while (m.find()){
                            String fileName = m.group(1);
                            String content = m.group(2);
                            List<String> list = null;
                            if(map.containsKey(content)){
                                list = map.get(content);
                            }else {
                                list = new ArrayList<>();
                            }
                            list.add(strings[0]+"/"+fileName);
                            map.put(content,list);
                        }
                    }
                }
            }
    
            List<List<String>> resultList = new ArrayList<>();
            for(String key:map.keySet()){
                if(map.get(key).size()>1){
                    resultList.add(map.get(key));
                }
            }
            return resultList;
        }
    }
    

    我直接应用正则表达式进行匹配,可以同时获取到文件名以及内容。
    Pattern p = Pattern.compile("(.\.txt)\((.)\)");

    String fileName = m.group(1);
    String content = m.group(2);

    欢迎批评指正


  • 0
    M

    If you keep using languages other than English in the forum, your post will likely be deleted. Just FYI.


  • 0
    L

    @Mr.Crazy

    I'm so sorry to hear that.My English is not good,but I like coding and share my solution.I think the most important thing is to share my idea and code.Using Chinese is to help me share them exactly.I will try my best to use English to describe my solution. Thanks for your reminding me~


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.