Simple Java Solution


  • 1
    R
    public class Solution {
        public int findLUSlength(String[] strs) {
            if(isEqual(strs)) return -1;
            
            Arrays.sort(strs, (a, b) -> Integer.compare(b.length(), a.length()));
            
            for(int i = 0; i < strs.length; ++i) {
                String first = strs[i];
                boolean flag = true;
                for(int j = 0; j < strs.length; ++j) {
                    if(j == i) continue;
                    String second = strs[j];
                    if(first.equals(second) || charMatch(first, second)) {
                        flag = false;
                        break;
                    }
                }
                if(flag) return first.length();
            }
            
            return -1;
        }
        
        private boolean charMatch(String first, String second) {
            int index = -1;
            for(int k = 0; k < first.length(); k++) {
                char c = first.charAt(k);
                index = second.indexOf(c, index + 1);
                if(index == -1) return false;
            }
            return true;
        }
        
        public boolean isEqual(String[] strs) {
            for(int i = 1; i < strs.length; ++i) {
                if(strs[i - 1].equals(strs[i])) continue;
                return false;
            }
            return true;
        }
    }
    
    

  • 0
    B

    @rsrs3 Hi I have a question. Why first.equals(second) isn't enough and you are checking also this charMatch(first, second) function?


Log in to reply
 

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