腾讯 2017 暑假实习生编程题(二):小Q最近遇到了一个难题:把一个字符串的大写字母放到字符串的后面,各个字符的相对位置不变,且不能申请额外的空间。 你能帮帮小Q吗?

题目

由《剑指 offer》面试题 4:替换空格,想到的技巧。

此处运用了一个小小的技巧:从后往前将大写字符依次插入数组尾部,时间复杂度 O(n) 。

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Scanner;

public class Main {

    private static char[] work(String str) {
        int length = str.length();
        int upCount = 0;    // 存储字符串中大写字母的个数
        // 循环查找字符串中大写字母的个数
        for (int index = 0; index < length; index++) {
            char temp = str.charAt(index);
            if (temp >= 'A' && temp <= 'Z') {
                upCount++;
            }
        }
        // 扩大字符数组的空间(原大小 + 大写字母个数)
        for (int index = 0; index < upCount; index++) {
            str += " ";
        }
        char[] chars = str.toCharArray();
        // 从后往前遍历,将遇到大写字母依次(从后往前)填充到末尾的空格
        for (int indexI = length - 1, indexJ = length + upCount - 1; indexI >= 0; indexI--) {
            if (chars[indexI] >= 'A' && chars[indexI] <= 'Z') {
                chars[indexJ--] = chars[indexI];
                chars[indexI] = ' ';
            }
        }
        return chars;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        String inputStr;
        while (in.hasNext()) {
            inputStr = in.next();
            for(char c: work(inputStr)){
                if(c != ' '){
                    out.print(c);
                }
            }
            out.println();
        }
        out.flush();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值