LoginSignup
0
0

More than 5 years have passed since last update.

POH6+ C# 解答

Last updated at Posted at 2015-09-05

例によってC#でクリアした。最短を目指すならアルゴリズム別なのがいいかな。
C#の文字列反転の煩雑さは困る。自分で書くと早くなるとかもう分かってるんだから内部実装もそうしてほしい。

アルゴリズム

0.仮登録HashSetと答えListを用意する
1.単語を1つ読み出す
2.HashSetになければ、反転した文字をHashSetに登録
3.HashSetにあれば、HashSetから消し、その単語の反転と比較しアルファベット順で早い方をListに入れる
4.単語の残りがあれば1に戻る
5.ABCBAのような、1単語で反転してる単語をHashSetからアルファベット順に早いのを探してcenterに入れる
6.Listをソートする
7.List+center+Listの反転を標準出力に書く

using System;
using System.Collections.Generic;
using System.Linq;
class B
{
    static void Main(string[] args)
    {
        List<string> ans = new List<string>();
        HashSet<string> l = new HashSet<string>();
        int N = int.Parse(Console.ReadLine());
        //int N = 6;
        //string[] input = new string[] { "fdk", "jnv", "vnj", "kdf", "qaq", "aaa" };
        //string[] input = new string[] { "sk", "nw", "jx", "ob", "oo", "xj",
        //    "uh", "rn", "wn", "hu", "nr" };
        for (int i = 0; i < N; i++)
        {
            var w = Console.ReadLine();
            //var w = input[i];
            var r = new string(w.Reverse().ToArray());
            if (l.Contains(w))
            {
                l.Remove(w);
                ans.Add(w.CompareTo(r) > 0 ? r : w);
            }
            else
            {
                l.Add(r);
            }
        }
        string c = "";
        if (l.Count > 0)
        {
            int len = l.First().Length;
            foreach (var s in l)
            {
                int start = 0, end = len - 1;
                bool isOk = true;
                for (int i = 0; i < len / 2; i++,start++,end--)
                {
                    if (s[start] != s[end])
                    {
                        isOk = false;
                        break;
                    }
                }
                if (isOk)
                {
                    if (c.Length == 0 || s.CompareTo(c) < 0)
                    {
                        c = s;
                    }
                }
            }
        }
        ans.Sort();
        var prefix = string.Join("",ans);
        var suffix = new string(prefix.Reverse().ToArray());
        Console.WriteLine(prefix+c+suffix);
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0