/**
1890 · Form Minimum Number
Algorithms
Medium
Accepted Rate
61%
DescriptionSolutionNotesDiscussLeaderboard
Description
Given a pattern str containing only I and D. I for increasing and D for decreasing. Please design an algorithm to return the string that conforms to the pattern and has the smallest dictionary order. Digits from 1 to 9 and digits can’t repeat.
1<=|str|<=8
Example
Example 1:
Input:
“D”
Output:
“21”
Explanation:
2>1
Example 2:
Input:
“II”
Output:
“123”
Explanation:
1<2<3
Example 3:
Input:
“DIDI”
Output:
“21435”
Example 4:
Input:
“DDIDDIID”
Output:
“321654798”
Tags
Company
Amazon
https://blog.csdn.net/qq_46105170/article/details/111027516
https://www.lintcode.com/problem/1890/
*/
/**
* @param str: the pattern
* @return: the minimum number
*/
func formMinimumNumber (str string) string {
// Write your code here.
var res string = ""
for i := 0; i < len(str) + 1; i++ {
res += string('0' + i + 1)
}
for i := 0; i < len(str); i++ {
if string(rune(str[i])) == "D" {
var j int = i
for {
if !(j < len(str) && string(rune(str[j])) == "D") {
break
}
j += 1
}
res = reverse(res, i, j)
i = j
}
}
return res
}
func reverse(res string, i, j int) string {
var resArr []uint8 = make([]uint8, len(res))
for k := 0; k < len(res); k++ {
resArr[k] = res[k]
}
for ; i < j; i++ {
var tmp uint8 = resArr[i]
resArr[i] = resArr[j]
resArr[j] = tmp
j--
}
var trans string = ""
for k := 0; k < len(res); k++ {
trans += string(rune(resArr[k]))
}
return trans
}