LeetCode Solutions
899. Orderly Queue
Time: Space:
class Solution {
public:
string orderlyQueue(string S, int K) {
if (K > 1) {
sort(begin(S), end(S));
return S;
}
string ans = S;
for (int i = 1; i < S.length(); ++i)
ans = min(ans, S.substr(i) + S.substr(0, i));
return ans;
}
};
class Solution {
public String orderlyQueue(String S, int K) {
if (K > 1) {
char[] chars = S.toCharArray();
Arrays.sort(chars);
return String.valueOf(chars);
}
String ans = S;
for (int i = 1; i < S.length(); ++i) {
String S2 = S.substring(i) + S.substring(0, i);
if (ans.compareTo(S2) > 0)
ans = S2;
}
return ans;
}
}
class Solution:
def orderlyQueue(self, S: str, K: int) -> str:
return ''.join(sorted(S)) if K > 1 else min(S[i:] + S[:i] for i in range(len(S)))