Iam_Sandeep

1849. Splitting a String Into Descending Consecutive Values

Jul 24th, 2022 (edited)
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.53 KB | None | 0 0
  1. '''
  2. You are given a string s that consists of only digits.
  3.  
  4. Check if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1.
  5.  
  6. For example, the string s = "0090089" can be split into ["0090", "089"] with numerical values [90,89]. The values are in descending order and adjacent values differ by 1, so this way is valid.
  7. Another example, the string s = "001" can be split into ["0", "01"], ["00", "1"], or ["0", "0", "1"]. However all the ways are invalid because they have numerical values [0,1], [0,1], and [0,0,1] respectively, all of which are not in descending order.
  8. Return true if it is possible to split s​​​​​​ as described above, or false otherwise.
  9.  
  10. A substring is a contiguous sequence of characters in a string.
  11. '''
  12. class Solution:
  13.     def splitString(self, s: str) -> bool:
  14.         n=len(s)
  15.         def dfs(i,prev):
  16.             if i==n:
  17.                 return True
  18.            
  19.             for j in range(i,n):#Here we need not go for min 2 partitions just min 1 parition also enough
  20.                 val=int(s[i:j+1])
  21.                 if val+1==prev and dfs(j+1,val):
  22.                     return True
  23.             return False
  24.            
  25.         for i in range(n-1):# At least we need 2 paritions at level 1 so. We do the partition to n-2
  26.             val=int(s[:i+1])
  27.             if dfs(i+1,val):return True
  28.         return False
  29.            
  30.        
Add Comment
Please, Sign In to add comment