一道面试题:输入:s = “codeleet“, indices = [4,5,6,7,0,2,1,3] 输出:“leetcode“

本文介绍了一种将字符串按特定索引顺序重新排列的方法。通过两种不同的实现方式,将原始字符串codeleet根据索引数组[4,5,6,7,0,2,1,3]重新排列为leetcode。第一种方法是先将字符串转换为字符数组,再根据索引创建新的字符串;第二种方法则是直接利用给定的索引进行字符赋值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、题目:

image-20201120111605454
输入:s = "codeleet", indices = [4,5,6,7,0,2,1,3]
输出:"leetcode"
解释:如图所示,"codeleet" 重新排列后变为 "leetcode"

2、代码

方式一:

方法一:将String 转换成字符数组chars, 然后创建一个新的字符数组result,长度为字符串的长度,接着以induces数组的值作为新字符串result的索引,值为chars中的元素

image-20201120111523726

package review;
public class Solution1 {
    public static String restoreString(String s,int[] indices){
        /**
         * indices:  4   5  6  7  0  2  1  3
         * chars  : [c, o, d, e, l,  e, e, t]
         */
        char[] chars = s.toCharArray();//[c, o, d, e, l, e, e, t]
        char[] result = new char[s.length()];
        int j = 0;
        //indices:4 5 6 7 0 2 1 3
        for (int i: indices) {
            result[i] = chars[j++];
           
        }
        return new String(result);
    }

    public static void main(String[] args) {
        String s = "codeleet";
        //System.out.println("char[] chars"+ Arrays.toString(chars));
        int[] indices ={4,5,6,7,0,2,1,3};
        System.out.println(restoreString(s, indices));
    }
}

方式二:

package review;
public class Solution1 {
    public static String restoreString(String s,int[] indices){
        //方法二:
        char[] ans = new char[s.length()];
        for (int i = 0; i < s.length(); i++) {
            ans[indices[i]] = s.charAt(i);
        }
        return new String(ans);
    }

    public static void main(String[] args) {
        String s = "codeleet";
        //System.out.println("char[] chars"+ Arrays.toString(chars));
        int[] indices ={4,5,6,7,0,2,1,3};
        System.out.println(restoreString(s, indices));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值