题解 | #小红的字符串构造#

小红的字符串构造

https://www.nowcoder.com/practice/3e4b4dabc2e444e384c3ae62ac7dd84e

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.next();
 
        // 使用 LinkedHashSet 以保持插入顺序
        Set<Character> uniqueChars = new LinkedHashSet<>();
 
        // 将字符串s的每个字符添加到Set中以去除重复字符
        for (char c : s.toCharArray()) {
            uniqueChars.add(c);
        }
        //就一个字符肯定没法弄
        if(uniqueChars.size()==1) System.out.println(-1);
        else{
            // 将Set转换为List来创建映射
        List<Character> uniqueCharsList = new ArrayList<>(uniqueChars);
 
        // 创建映射
        Map<Character, Character> mapping = new HashMap<>();
        int size = uniqueCharsList.size();
        for (int i = 0; i < size; i++) {
            // 将当前字符映射到下一个字符,最后一个字符映射到自己
            char currentChar = uniqueCharsList.get(i);
            char nextChar = uniqueCharsList.get((i + 1) % size); // 使用取模来循环到第一个字符
            mapping.put(currentChar, nextChar);
        }
 
        // 构建新的字符串t
        StringBuilder tBuilder = new StringBuilder();
        for (char c : s.toCharArray()) {
            tBuilder.append(mapping.get(c));
        }
        String t = tBuilder.toString();
 
        // 输出新字符串
        System.out.println(t);
        }
         
 
        in.close();
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
07-09 20:50
门头沟学院 Java
码农索隆:1.教育背景和荣誉证书合二为一。 2.获奖项目理一遍,你做了什么,对你求职的岗位有什么帮助,没有就删掉。 3.技能特长和教育背景交换位置。 4.技能特长写的太差,上网上找简历参考。都不用问你别的,一个redis就能把你问住,写写你具体会redis哪些方面的知识。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务