1、给定整数n和m, 将1到n的这n个整数按字典序排列之后, 求其中的第m个数。
对于n=11, m=4, 按字典序排列依次为1, 10, 11, 2, 3, 4, 5, 6, 7, 8, 9, 因此第4个数是2.
long res = getAnswer(n, 1, m-1);
class Solution
{
public static long getAnswer(long n, long cur, long steps)
{
while(steps > 0)
{
long curstep = getSteps(n, cur, cur+1);
if(curstep <= steps)
{
steps = steps - curstep;
cur++;
}
else
{
steps--;
cur = cur*10;
}
}
return cur;
}
public static long getSteps(long n, long a, long b)
{
long res = 0;
while(a <= n)
{
res = res + Math.min(n+1, b) - a;
a = a * 10;
b = b * 10;
}
return res;
}
}
2、假定一种编码的编码范围是a ~ y的25个字母,从1位到4位的编码,如果我们把该编码按字典序排序,形成一个数组如下: a, aa, aaa,aaaa, aaab, aaac, … …, b, ba, baa, baaa, baab, baac … …, yyyw, yyyx,yyyy 其中a的Index为0,aa的Index为1,aaa的Index为2,以此类推。
public class Main
{
public static int getAnswer(String s)
{
return dfs("a", s, 0);
}
public static int dfs(String a, String b, int pos)
{
if(pos == b.length()) return 0;
if(pos == a.length())
{
a = a + 'a';
return 1 + dfs(a, b, pos);
}
if(a.charAt(pos) == b.charAt(pos))
{
return dfs(a, b, pos+1);
}
char c1 = a.charAt(pos);
char c2 = b.charAt(pos);
int count = 0;
int cnt = 4-1-pos;
while(cnt >= 0)
{
count = count + (int)Math.pow(25, cnt);
cnt--;
}
StringBuffer sb = new StringBuffer(a);
sb.setCharAt(pos, c2);
a = sb.toString();
return count*(c2-c1) + dfs(a, b, pos+1);
}
}