题意:给出一个字符串,问需要几个栈,来使得每个栈的字符串按字典序方式存在栈中
思路:在遍历字符串时,在当前的几个栈中找到满足当前字符小于栈顶字符,并且与栈顶字符距离最近。
代码如下:
import java.io.BufferedInputStream;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
private int solver(String s)
{
char[] chars = s.toCharArray();
int[] stacks = new int[chars.length];
int cnt = 0;
for (int i = 0; i < chars.length; i++)
{
boolean found = false;
int ch = chars[i] - 'A' + 1;
int max = Integer.MAX_VALUE;
int curpos = 0;
for (int j = 0; j < cnt; j++)
{
if (stacks[j] >= ch)
{
found = true;
if (stacks[j] - ch < max)
{
max = stacks[j] - ch;
curpos = j;
}
}
}
if (found)
{
stacks[curpos] = ch;
}
else
{
stacks[cnt++] = ch;
}
}
return cnt;
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(new BufferedInputStream(System.in));
Main solver = new Main();
int cas = 1;
while (scanner.hasNext())
{
String s = scanner.nextLine();
if ("end".compareTo(s) == 0) break;
int ans = solver.solver(s);
System.out.println("Case " + cas++ + ": " + ans);
}
}
}