字典序

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);
    }
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值