https://leetcode.com/problems/longest-uncommon-subsequence-ii/description/

코드설명

구현(Implementation) + 문자열(Substring)을 활용합니다.

 

가장 긴 일치하지 않는 공통부분수열의 길이를 구하는 문제입니다.

먼저, 구하기 위해 가장 긴 순서대로 Strs를 정렬합니다.

 

이후에 Strs를 순회하면서 다른 문자열들과 common 한지를 먼저 확인해보면서, 만약 다른 모든 String과 비교했을떄 모두 Uncommon 하다면, Uncommon Subseuqnece 이므로 값의 길이를 반환합니다. (이미 긴 순서대로 정렬되어있기에 상관 없습니다.)

코드

class Solution {
    public int findLUSlength(String[] strs) {
        Arrays.sort(strs, new Comparator<String>(){
            @Override
            public int compare(String s1, String s2){
                return Integer.compare(s2.length(), s1.length());
            }
        });

        for(int i=0; i<strs.length; i++){
            boolean isUncommon = true;
            for(int j=0; j<strs.length; j++){
                if(i == j) continue;
                if(isSubsequence(strs[i], strs[j]) == true){
                    isUncommon = false;
                    break;
                }
            }
            if(isUncommon == true){
                return strs[i].length();
            }
        }
        return -1;
    }

    public boolean isSubsequence(String s1, String s2){
        int i = 0, j = 0;
        while(i < s1.length() && j < s2.length()){
            if(s1.charAt(i) == s2.charAt(j)){
                i+=1;
            }
            j+=1;
        }

        return s1.length() == i;
    }

}

+ Recent posts