tutorialcup
Reformat The String Leetcode Solution
Problem Statement
In this problem, we are given an alphanumeric string i.e. the string has only lowercase alphabets (a-z) and digits(0-9). We are required to return any permutation of this string, in which there is no consecutive alphabet in it or no consecutive digits. If no such permutation is there, then we have to return an empty string.
Example
s = "a0b1c2"
"0a1b2c"
Explanation:
No two adjacent characters have the same type in "0a1b2c".
"a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations.
s = "leetcode"
""
Explanation:
"leetcode" has only characters so we cannot separate them by digits.
Approach
Let's first understand the condition in which we can return a permutation.
Suppose if string is "abcde" then we can't make any possible permutation from it in which no two alphabets or numbers are consecutive.
Similarly if string is "12335" then also we can't do anything.
So, to make alternative alphanumeric string, should we have equal number of digits and alphabets?
No, Let's see example "covid2019" we have 5 alphabets and 4 digits.
Still we have possible ans e.g. "c2o0v1i9d".
Now if there would be one more alphabet in the same string, let "covids2019" then also we could not form any possible output.
Thus here we have got a condition that difference of count of alphabets and count of digits should not exceed 1.
i.e. abs(count(digits)-count(alphabets))
www.tutorialcup.com/leetcode-solutions/reformat-the-strin...
Reformat The String Leetcode Solution
Problem Statement
In this problem, we are given an alphanumeric string i.e. the string has only lowercase alphabets (a-z) and digits(0-9). We are required to return any permutation of this string, in which there is no consecutive alphabet in it or no consecutive digits. If no such permutation is there, then we have to return an empty string.
Example
s = "a0b1c2"
"0a1b2c"
Explanation:
No two adjacent characters have the same type in "0a1b2c".
"a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations.
s = "leetcode"
""
Explanation:
"leetcode" has only characters so we cannot separate them by digits.
Approach
Let's first understand the condition in which we can return a permutation.
Suppose if string is "abcde" then we can't make any possible permutation from it in which no two alphabets or numbers are consecutive.
Similarly if string is "12335" then also we can't do anything.
So, to make alternative alphanumeric string, should we have equal number of digits and alphabets?
No, Let's see example "covid2019" we have 5 alphabets and 4 digits.
Still we have possible ans e.g. "c2o0v1i9d".
Now if there would be one more alphabet in the same string, let "covids2019" then also we could not form any possible output.
Thus here we have got a condition that difference of count of alphabets and count of digits should not exceed 1.
i.e. abs(count(digits)-count(alphabets))
www.tutorialcup.com/leetcode-solutions/reformat-the-strin...