您的位置:首页 > 职场人生

一个C#面试问题,要求是将字符串中重复字符从第二个开始都去掉,空格除外。然后显示的时候,从后往前显示。

2014-05-12 10:21 756 查看
因为C#的code,感觉实现这个还是比较容易,只是SB。所以,在面试时候,以为不会这么容易,所以,我先试着用了Dictionary去实现,发现有困难。然后改回来用StringBuilder实现,这个因为比较简单了,总以为这样会有问题。所以不知道这样是不是对的。

结果当然很不理想,我准备后面学习一下C++,看看这个题目用C++实现有什么值得注意的地方。还是有什么精华所在。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication9
{
class Program
{
public static void DeDupAndReverse(string str)
{
char blank = ' ';
StringBuilder sbDeDup = new StringBuilder();/// SB which will be de dupped.
StringBuilder sbReverse = new StringBuilder(); /// sb which will be used for reverse

for (int index = 0; index < str.Length; index++)
{
if ((!((sbDeDup.ToString()).Contains(str[index])) || (str[index].Equals(blank)))) /// chars contailed in the SB will be dedupped except for blank spance
{
sbDeDup.Append(str[index]);
}
else
{
continue;
}
}

for (int index = sbDeDup.Length -1; index >= 0; index--)
{
sbReverse = sbReverse.Append(sbDeDup[index]);   //reverse the sb
}

for (int index = 0; index < sbReverse.Length; index++)
{
System.Console.Write(sbReverse[index]); /// write the SB to the console
}
}

public static void Main(string[] args)
{
string str = "Hello World"; /// one test string.

DeDupAndReverse(str); /// call the method to run a test.

Console.ReadLine();
}
}
}


吸收了一些人的评论,此处没有写注释。更新code如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication9
{
class Program
{
public static string ProcessString(string input)
{
StringBuilder sb = new StringBuilder();
HashSet<char> hashSet=new HashSet<char>();
foreach (var c in input)
{
if (c == ' ')
{
sb.Append(c);
}
if (hashSet.Contains(c)==false)
{
sb.Append(c);
hashSet.Add(c);
}
}
return sb.ToString();
}

public static string DeDeup_Reverse(string toBeProcessed)
{
string toBeReversed = ProcessString(toBeProcessed);
StringBuilder sbReversed = new StringBuilder(toBeReversed.Length);

for (int i = toBeReversed.Length - 1; i >= 0; i--)
{
sbReversed.Append(toBeReversed[i]);
}

return sbReversed.ToString();
}

public static void Main(string[] args)
{
string str = "Hello World, hello world";

Console.WriteLine(DeDeup_Reverse(str));

Console.ReadLine();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐