java -贪心
给定一个字符串,一个K
可以交换相邻字符,最多K次。问可以得到的最大值
如
String s = "01326";
int k = 7;
01326-->60132-->63012-->63102
import java.util.*; public class Main { public static void main(String[] args) { String s = "01326"; int k = 7; int l = s.length(); int id = 0; while (id < l && k > 0) { int kk = Math.min(k, l - id); int num = s.charAt(id) - '0'; System.out.println("kk " + kk + " num: " + num); int tmpk = kk; for (int i = id + 1; i < id + kk; i++) { System.out.println("i " + i); if (num < (s.charAt(i) - '0')) { num = s.charAt(i) - '0'; tmpk = i - id; } } kk = tmpk; String s1 = s.substring(0, id); String s2 = s.substring(id, id + kk); String s3 = s.substring(id + kk + 1, l); s = s1 + s.charAt(id + kk) + s2 + s3; System.out.println("s " + s); k -= kk; id++; } System.out.println(s); } }