We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
public static String biggerIsGreater(String w) {
char[] chars = w.toCharArray();
int i = chars.length - 2;
// Step 1: Find the first character that is smaller than its next character from the end
while (i >= 0 && chars[i] >= chars[i + 1]) {
i--;
}
if (i < 0) {
return "no answer";
}
// Step 2: Find the smallest character on the right of i that is greater than chars[i]
int j = chars.length - 1;
while (chars[j] <= chars[i]) {
j--;
}
// Step 3: Swap them
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
// Step 4: Reverse the suffix starting at i + 1
int left = i + 1, right = chars.length - 1;
while (left < right) {
temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
return new String(chars);
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int T = Integer.parseInt(bufferedReader.readLine().trim());
IntStream.range(0, T).forEach(TItr -> {
try {
String w = bufferedReader.readLine();
String result = Result.biggerIsGreater(w);
bufferedWriter.write(result);
bufferedWriter.newLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});
bufferedReader.close();
bufferedWriter.close();
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Bigger is Greater
You are viewing a single comment's thread. Return to all comments →
import java.io.; import java.util.; import java.util.stream.*;
class Result {
}
public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
}