Java solution with hashmap and set (10ms)


  • 0
    W
    1. use hashmap to caculate the str appear times, and add the repeated strs to hashset.
    2. for each strs array, only focus on the single str. judge curstr is subseq of the str in the set or not.if not, caculate length of the word.
    3. end.follow is the Java code, only 10ms.
    public class Solution {
        private Set<String> set;
    
        public int findLUSlength(String[] strs) {
            set = new HashSet<String>();
            Map<String, Integer> map = new HashMap<String, Integer>();
            int len = strs.length;
            for (int i = 0; i < len; i++) {
                Integer num = map.get(strs[i]);
                if (num == null) {
                    num = 1;
                } else {
                    num += 1;
                    set.add(strs[i]);
                }
                map.put(strs[i], num);
            }
            int maxLen = -1;
            for (int i = 0; i < len; i++) {
                Integer num = map.get(strs[i]);
                if (num == 1) {
                    if (isSubseq(strs[i])) {
                        continue;
                    }
                    int curLen = strs[i].length();
                    maxLen = maxLen > curLen ? maxLen : curLen;
                }
            }
            return maxLen;
        }
    
        private boolean isSubseq(String curStr) {
            boolean flag = false;
            int len1 = curStr.length();
            for (String str : set) {
                int j = 0;
                int k = 0;
                int len2 = str.length();
                if (len1 > len2) {
                    return flag;
                }
                while (j < len2 && k < len1) {
                    if (curStr.charAt(k) == str.charAt(j)) {
                        k++;
                    }
                    j++;
                }
                if (k == len1) {
                    flag = true;
                    break;
                }
            }
            return flag;
        }
    }
    

Log in to reply
 

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