从右往左遍历,遇到小的就删:
import java.util.*; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); StringBuilder sb = new StringBuilder(sc.nextLine()); char last = sb.charAt(sb.length() - 1); int i = sb.length() - 2; while(i >= 0){ if(sb.charAt(i) >= last){ last = sb.charAt(i); i--; }else{ sb.deleteCharAt(i); } } System.out.println(sb); } }