华为OD机试真题-字符串变换最小字符

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int maxCount = Integer.parseInt(in.nextLine());
        String word = in.nextLine();
        System.out.println(getResult(word, maxCount));
    }

    public static String getResult(String word, int maxCount) {
        StringBuilder wordBuilder = new StringBuilder(word);

        int i = 0;
        int index = 0;
        int left = 0, right = 0;
        StringBuilder ans = new StringBuilder();
        while (i < wordBuilder.length()) {
            if (wordBuilder.charAt(i) == '-') {
                index++;
                wordBuilder.delete(i, i + 1);

            }
            if (index == 1) {
                ans.append(wordBuilder.substring(0, i) + &quot;-&quot;);
                left = i;
                right++;
                i++;
                index++;
                continue;
            } else if (index > 0 &amp;&amp; right - left == maxCount){
                String temp = wordBuilder.substring(left, right);
                change(temp);
                ans.append(temp + &quot;-&quot;);
                left = i;
            }
            if (i == wordBuilder.length() - 1) {
                String temp = wordBuilder.substring(left, wordBuilder.length());
                change(temp);
                ans.append(temp + &quot;-&quot;);
            }
            right++;
            i++;
        }
        return ans.delete(ans.length()-1, ans.length()).toString();
    }

    public static void change(String word) {
        int low = 0;
        int uppper = 0;
        for (int i = 0; i < word.length(); i++) {
            if (word.charAt(i) >= 'a' &amp;&amp; word.charAt(i) <= 'z')
                low++;
            else if (word.charAt(i) >= 'A' &amp;&amp; word.charAt(i) <= 'Z')
                uppper++;
        }
        if (low > uppper)
            word.toLowerCase();
        if (uppper > low)
            word.toUpperCase();
    }
全部评论

相关推荐

06-25 09:33
厦门大学 Java
程序员饺子:现在日常估计没啥hc了,等到八月多估计就慢慢有了。双九✌🏻不用焦虑的
投递快手等公司8个岗位
点赞 评论 收藏
分享
流浪的神仙:无恶意,算法一般好像都得9硕才能干算法太卷啦
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-02 15:39
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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