Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversal and removing of duplicates in a sentence

Tags:

c#

I am preparing for a interview question.One of the question is to revert a sentence. Such as "its a awesome day" to "day awesome a its. After this,they asked if there is duplication, can you remove the duplication such as "I am good, Is he good" to "good he is, am I".

for reversal of the sentence i have written following method

public static string reversesentence(string one)
{
    StringBuilder builder = new StringBuilder();

    string[] split = one.Split(' ');
    for (int i = split.Length-1; i >= 0; i--)
    {

        builder.Append(split[i]);
        builder.Append(" ");
    }
    return builder.ToString();

}

But i am not getting ideas on removing of duplication.Can i get some help here.

like image 891
user1410658 Avatar asked Jul 15 '15 03:07

user1410658


2 Answers

This works:

public static string reversesentence(string one)
{
    Regex reg = new Regex("\\w+");
    bool isFirst = true;
    var usedWords = new HashSet<String>(StringComparer.InvariantCultureIgnoreCase);
    return String.Join("", one.Split(' ').Reverse().Select((w => {
        var trimmedWord = reg.Match(w).Value;
        if (trimmedWord != null) {
            var wasFirst = isFirst;
            isFirst = false;

            if (usedWords.Contains(trimmedWord)) //Is it duplicate?
                return w.Replace(trimmedWord, ""); //Remove the duplicate phrase but keep punctuation

            usedWords.Add(trimmedWord);

            if (!wasFirst) //If it's the first word, don't add a leading space
                return " " + w;
            return w;
        }
        return null;
    })));
}

Basically, we decide if it's distinct based on the word without punctuation. If it already exists, just return the punctuation. If it doesn't exist, print out the whole word including punctuation.

Punctuation also removes the space in your example, which is why we can't just do String.Join(" ", ...) (otherwise the result would be good he Is , am I instead of good he Is, am I

Test:

reversesentence("I am good, Is he good").Dump();

Result:

good he Is, am I

like image 114
Rob Avatar answered Sep 24 '22 01:09

Rob


For plain reversal:

String.Join(" ", text.Split(' ').Reverse())

For reversal with duplicate removal:

String.Join(" ", text.Split(' ').Reverse().Distinct())

Both work fine for strings containing just spaces as the separator. When you introduce the , then problem becomes more difficult. So much so that you need to specify how it should be handled. For example, should "I am good, Is he good" become "good he Is am I" or "good he Is , am I"? Your example in the question changes the case of "Is" and groups the "," with it too. That seems wrong to me.

like image 39
Enigmativity Avatar answered Sep 25 '22 01:09

Enigmativity