Input: s ="cba", k =1Output: "acb"Explanation:
In the first move, we move the 1st character 'c' to the end, obtaining the string "bac".In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb".
Example 2:
1
2
3
4
5
Input: s ="baaca", k =3Output: "aaabc"Explanation:
In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab".In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc".
If k == 1, we can only rotate the string by moving the first character to the end, so we must try all rotations and pick the smallest. If k > 1, we can rearrange the string in any order by repeatedly moving any of the first k characters to the end, so the answer is the sorted string.
classSolution {
public: string orderlyQueue(string s, int k) {
if (k ==1) {
string ans = s;
int n = s.size();
for (int i =1; i < n; ++i) {
string rotated = s.substr(i) + s.substr(0, i);
if (rotated < ans) ans = rotated;
}
return ans;
}
string ans = s;
sort(ans.begin(), ans.end());
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
public String orderlyQueue(String s, int k) {
if (k == 1) {
String ans = s;
int n = s.length();
for (int i = 1; i < n; ++i) {
String rotated = s.substring(i) + s.substring(0, i);
if (rotated.compareTo(ans) < 0) ans = rotated;
}
return ans;
}
char[] arr = s.toCharArray();
Arrays.sort(arr);
returnnew String(arr);
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
deforderlyQueue(self, s: str, k: int) -> str:
if k ==1:
ans: str = s
for i in range(1, len(s)):
rotated: str = s[i:] + s[:i]
if rotated < ans:
ans = rotated
return ans
return''.join(sorted(s))