原题出处:牛客网-腾讯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);
}
}
}