最大字典序
栈和排序
https://ac.nowcoder.com/acm/problem/14893
发一个java版本的
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] array = new int[n]; for(int i = 0; i < n; i++){ array[i] = sc.nextInt(); } int[] maxArray = new int[n]; maxArray[n - 1] = array[n - 1]; for(int i = n - 2; i >= 0; i--){ maxArray[i] = Math.max(array[i], maxArray[i + 1]); } Stack<Integer> stack = new Stack<>(); StringBuilder sb = new StringBuilder(); for(int i = 0; i < n; i++){ while(!stack.isEmpty() && stack.peek() > maxArray[i]){ //System.out.print(stack.pop() + " "); sb.append(stack.pop() + " "); } stack.push(array[i]); } while(!stack.isEmpty()){ //System.out.print(stack.pop() + " "); sb.append(stack.pop() + " "); } System.out.print(sb.toString()); } }