728x90
 

Delete Columns to Make Sorted - LeetCode

Delete Columns to Make Sorted - You are given an array of n strings strs, all of the same length. The strings can be arranged such that there is one on each line, making a grid. For example, strs = ["abc", "bce", "cae"] can be arranged as: abc bce cae You

leetcode.com

[문제 설명]

You are given an array of n strings strs, all of the same length.

The strings can be arranged such that there is one on each line, making a grid. For example, strs = ["abc", "bce", "cae"] can be arranged as:

abc
bce
cae

You want to delete the columns that are not sorted lexicographically. In the above example (0-indexed), columns 0 ('a', 'b', 'c') and 2 ('c', 'e', 'e') are sorted while column 1 ('b', 'c', 'a') is not, so you would delete column 1.

Return the number of columns that you will delete.

 

Example 1:

Input: strs = ["cba","daf","ghi"]
Output: 1
Explanation: The grid looks as follows:
  cba
  daf
  ghi
Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column.

Example 2:

Input: strs = ["a","b"]
Output: 0
Explanation: The grid looks as follows:
  a
  b
Column 0 is the only column and is sorted, so you will not delete any columns.

Example 3:

Input: strs = ["zyx","wvu","tsr"]
Output: 3
Explanation: The grid looks as follows:
  zyx
  wvu
  tsr
All 3 columns are not sorted, so you will delete all 3.

 

Constraints:

  • n == strs.length
  • 1 <= n <= 100
  • 1 <= strs[i].length <= 1000
  • strs[i] consists of lowercase English letters.

[문제 풀이]

위 문제는 입력으로 들어온 문자열들을 세로로 봤을때 사전식(오름차순)으로 정렬되어있는지 확인하고, 정렬되어 있지 않은 갯수를 세어 리턴하면 되는 간단한 문제다.

 

이중 반복문으로 각 문자열의 첫번째 열에 문자들부터 오름차순으로 정렬되어있는지 확인하고, 정렬되어있지 않다면

count를 증가시켜주고 break를 통해 다음 열을 확인한다.

 

위 방식을 문자열들의 마지막 열까지 확인하면서 count를 증가시켜주고, 마지막에 count값을 리턴해주면 된다. 

 

[코드]

[GitHub]

 

GitHub - EGyeom/ProblemSolving

Contribute to EGyeom/ProblemSolving development by creating an account on GitHub.

github.com

class Solution {
public:
    int minDeletionSize(vector<string>& strs) {
        int strs_size = strs.size();
        int str_size = strs[0].size();
        int count = 0;
        for(int i =0; i < str_size; i++)
        {
            for(int j = 0; j < strs_size-1; j++)
            {
                if(strs[j][i] > strs[j+1][i])
                {
                    count++;
                    break;
                }
            }
        }
        return count;
    }
};

 

'Problem Solving > LeetCode' 카테고리의 다른 글

[LeetCode] - 797. All Paths From Source to Target(C/C++)  (0) 2022.12.30
복사했습니다!