using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
public class WordDeduplicator
{
/// <summary>
/// Removes duplicate words from a free-text string containing Unicode characters.
/// Preserves word order and the case of the first occurrence.
/// </summary>
/// <param name="input">The input free-text string containing punctuation and Unicode words.</param>
/// <returns>A space-separated string of unique words.</returns>
public static string RemoveDuplicateWords(string input)
{
if (string.IsNullOrWhiteSpace(input))
{
return string.Empty;
}
// 1. \w+ matches any sequence of Unicode word characters (letters, digits, connector punctuation).
// Punctuation like !, ;, *, and spaces are automatically filtered out.
// Regex engine natively supports full Unicode character sets (Latin, Japanese, Greek, etc.).
MatchCollection matches = Regex.Matches(input, @"\w+");
// 2. Use a HashSet with OrdinalIgnoreCase to track seen words in O(1) time without extra allocations.
var seenWords = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
// 3. StringBuilder for efficient O(N) string construction.
var resultBuilder = new StringBuilder();
foreach (Match match in matches)
{
string word = match.Value;
// Add returns true if the element was added (meaning it's the first time we've seen it)
if (seenWords.Add(word))
{
if (resultBuilder.Length > 0)
{
resultBuilder.Append(' ');
}
resultBuilder.Append(word);
}
}
return resultBuilder.ToString();
}
public static void Main()
{
string input = "Hello! こんにちは, ,hello こんにちは Bună ziua; Γεια σας Bună ziua *HELLO* Γεια σας";
string result = RemoveDuplicateWords(input);
Console.WriteLine(result);
}
}
/*
run:
Hello こんにちは Bună ziua Γεια σας
*/