谷歌新题讨论 Delete Columns to Make Sorted III

Delete Columns to Make Sorted III

We are given an array A of N lowercase letter strings, all of the same length.

Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices.

For example, if we have an array A = ["babca","bbazb"] and deletion indices {0, 1, 4} , then the final array after deletions is ["bc","az"] .

Suppose we chose a set of deletion indices D such that after deletions, the final array has every element (row) in lexicographic order.

For clarity, A[0] is in lexicographic order (ie. A[0][0] <= A[0][1] <= ... <= A[0][A[0].length - 1] ), A[1] is in lexicographic order (ie. A[1][0] <= A[1][1] <= ... <= A[1][A[1].length - 1] ), and so on.

Return the minimum possible value of D.length .

Example 1:

Input: [“babca”,“bbazb”] Output: 3 Explanation: After deleting columns 0, 1, and 4, the final array is A = [“bc”, “az”]. Both these rows are individually in lexicographic order (ie. A[0][0] <= A[0][1] and A[1][0] <= A[1][1]). Note that A[0] > A[1] - the array A isn’t necessarily in lexicographic order.

Example 2:

Input: [“edcba”] Output: 4 Explanation: If we delete less than 4 columns, the only row won’t be lexicographically sorted.

Example 3:

Input: [“ghi”,“def”,“abc”] Output: 0 Explanation: All rows are already lexicographically sorted.

应该可以用 Longest Increasing Subsequence 的思路做。每个row 其实就是在求 Longest Increasing Subsequence, 但是cap在all row 的max length的最小值。

这题思路可以这样, m 个row 我们可以用m个ArrayList 来存 LIS。

		int m = A.length, n = A[0].length();
		List<List<Character>> dp = new ArrayList<>(m);
		for (int i = 0; i < m; i++) {
			List<Character> row = new ArrayList<>();
			row.add(A[i].charAt(0));
			dp.add(row);
		}

假设input 是 “babca”,“bbazb”:
col = 0, c1 = b, c2 = b
[“b”]
[“b”]

col = 1, c1 = a, c2 = b
通过 binary search,c1 需要replace
[“a”]
[“b”]

col = 2, c1 = b, c2 = a
通过 binary search,c2 需要replace
[“b”]
[“a”]

col = 3, c1 = c, c2 = z
通过 binary search,可以都append。此时最大长度为2 了。
[“b”, “c”]
[“a”, “z”]

col = 4, c1 = a, c2 = b
通过 binary search,c1和c2都需要replace。
[“a”, “c”]
[“b”, “z”]