Today, I found there is a interesting post in Stack Overflow, duplicate character removal. This is mean, there is string like “sueijdesyebhsdewqw”, the ‘w’ is the duplicate character, so it would be removed. This is a easy question, the purpose of this post is to give a faster, shorter and more elegant solution for it.
In .NET, LINQ is a useful and powerful tool, sometimes you may ignore it, just use it to manipulate the XML,Database or List. But do not forget that the string is also a Enumerable class. You can leverage it to manipulate the string also.
C#
var str = "serrfguikntedbctqes";
var duplicate = str.Where(ch => str.Count(c => c == ch) > 1);
var result = new string(str.Except(duplicate).ToArray());
And you can use the Group to group the character in the string and pick out the suitable group from string.
C#
StringBuilder sb = new StringBuilder();
foreach (var s in str.ToArray().GroupBy(c => c))
{
if (s.Count() == 1)
sb.Append(s.Key);
}
If you are not familiar with the LINQ, the first idea comes out of your brain may be similar with the one below,
C#
var h1 = new HashSet<char>();
var h2 = new HashSet<char>();
foreach (var c in str)
{
if (!h1.Add(c))
{
h2.Add(c);
}
}
h1.ExceptWith(h2);
result = new string(h1.ToArray());
If you are fan of Javascript, you may like it
Javascript
s.split('').filter(function (o,i,a) a.filter(function(p) o===p).length <2 ).join('');
Don’t forget the Perl which is very good at the text process and regular express.
Perl
perl -pe's/$1//gwhile/(.).*\1/'
You may wonder where is the C language, be patient.
C language
#ifdef NICE_LAYOUT
#include <stdio.h>
/* global variables are initialized to 0 */
int char_count[256]; /* k in the other layout */
int char_order[999999]; /* o ... */
int char_index; /* p */
int main(int ch_n_loop, char **dummy) /* c */
/* variable with 2 uses */
{
(void)dummy; /* make warning about unused variable go away */
while ((ch_n_loop = getchar()) >= 0) /* EOF is, by definition, negative */
{
++char_count[ ( char_order[char_index++] = ch_n_loop ) ];
/* assignment, and increment, inside the array index */
}
/* reuse ch_n_loop */
for (ch_n_loop = 0; ch_n_loop < char_index; ch_n_loop++) {
(char_count[char_order[ch_n_loop]] - 1) ? 0 : putchar(char_order[ch_n_loop]);
}
return 0;
}
#else
k[256],o[999999],p;main(c){while((c=getchar())>=0)++k[o[p++]=c];for(c=0;c<p;c++)k[o[c]]-1?0:putchar(o[c]);}
#endif
But the most amazing solution for it is using the LabVIEW 7.1
Actually, there are lots of interesting solutions for this problem, but some of them are too tricky to use in practice. Anyway, you still get some tips and fun from these solution.
Reference link1,link2
No comments:
Post a Comment