【编程题】算法基础-字符移位

原题出处:牛客网-腾讯2017暑期实习生编程题

[编程题] 算法基础-字符移位
时间限制:1秒

空间限制:32768K

小Q最近遇到了一个难题:把一个字符串的大写字母放到字符串的后面,各个字符的相对位置不变,且不能申请额外的空间。
你能帮帮小Q吗?

输入描述:

输入数据有多组,每组包含一个字符串s,且保证:1<=s.length<=1000.

输出描述:

对于每组数据,输出移位后的字符串。

输入例子1:
AkleBiCeilD

输出例子1:
kleieilABCD

解题思路:
 按序找出字符串中的大写字母并将其移动到字符串尾部,需要提前检测字符串中大写字母的长度。

更简单的思路…:
 按序输出字符串中的小写字母后按序输出字符串中的大写字母…

一下为题解:

using System;

public class Program
{
  // Move the Uppercase char to the str's tail.
    public static string MoveUppercase(string str, int index)
    {
        char c = str[index];
        char[] cStr = str.ToCharArray();
        int i = index;
        for (; i < str.Length-1; i++)
        {
            cStr[i] = cStr[i + 1];
        }
        cStr[i] = c;

        string result = new string(cStr);
        return result;
    }

    public static string HandleUppercase(string str)
    {
      // calculate the amount of uppercase in the str.
        int upperCount = 0;
        for (int i = 0; i < str.Length; i++)
        {
            if (Char.IsUpper(str[i]))
                upperCount++;
        }
        if (upperCount == 0)
            return str;

        int t = 0;
        for (int i = 0; i < str.Length; i++)
        {
            if(Char.IsUpper(str[i]))
            {
                str = MoveUppercase(str, i);
                i--;
                t++;
                if (t >= upperCount)
                    break;
            }
        }

        return str;
    }

    public static void Main(string[] args)
    {
        string str;
        while((str = Console.ReadLine()) != null)
        {
            string result = HandleUppercase(str);
            Console.WriteLine(result);
        }
    }
}

更简单的题解:

using System;

public class Program
{
    static void HandleOutput(string str)
    {
        for(int i=0; i<str.Length; i++)
        {
            if(Char.IsLower(str[i]))
                Console.Write(str[i]);
        }

        for(int i=0; i<str.Length; i++)
        {
            if(Char.IsUpper(str[i]))
                Console.Write(str[i]);
        }
        Console.WriteLine();
    }

    public static void Main(string[] args)
    {
        string str;
        while((str = Console.ReadLine()) != null)
        {
            HandleOutput(str);
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值