给定长度相同的字符串数组arr [] ,任务是计算要删除的列数,以便对所有行进行字典排序。
例子:
Input: arr[] = {“hello”, “geeks”}
Output: 1
Deleting column 1 (index 0)
Now both strings are sorted in lexicographical order i.e. “ello” and “eeks”.
Input: arr[] = {“xyz”, “lmn”, “pqr”}
Output: 0
All rows are already sorted lexicographically.
方法:问题的想法是找到要保留的列,而不是要删除的列。最后,我们返回计数值与字符串长度的差。
现在,假设我们保留第一列C1 。下一列C2我们必须具有所有行排序按字典顺序即C 1 [I] <= C2 [I]对于i的所有有效值和我们说我们已删除C1和C2之间的所有列。
下面是上述方法的实现:
# Python3 implementation of the approach
# Function to find minimum columns to be deleted
def deleteColumns(A):
# Length of each string
l = len(A[0])
# Initialize dp array
dp = [1] * l
for i in range(l - 2, -1, -1):
for j in range(i + 1, l):
if all(row[i] <= row[j] for row in A):
dp[i] = max(dp[i], 1 + dp[j])
# Return result
return l - max(dp)
# Driver Code
arr = ["hello", "geeks"]
# Function call to print required answer
print(deleteColumns(arr))
输出:
1