1. 程式人生 > >Leetcode557 反轉字串中的單詞III c#

Leetcode557 反轉字串中的單詞III c#

        static void Main(string[] args)
        {
            string str = "Let's take LeetCode contest";
            string stres = Get557(str);
            Console.WriteLine(stres);
            Console.ReadKey();
        }

        #region 557. 反轉字串中的單詞 III
        private static string Get557(string str)
        {
            string strs = "";
            string[] ch = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < ch.Length; i++)
            {
              strs+=  Getpps(ch[i])+" ";
            }
            return strs;
        }

        private static string Getpps(string p)
        {
            string s = "";
            char[] c = p.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                s += c[i];
            }
            return s;
        } 
        #endregion

可以參考以上的方法,容易理解,但在LeetCode 上超出記憶體限制

c# 本身提供了很多語法糖,方便操作。請參考一下程式碼:(2018/11/4)

        public static string ReverseString(string s)
        {
            var words = s.Split(' ');
            var res = new StringBuilder();
            foreach (var word in words)
            {
                res.Append(word.Reverse().ToArray());
                res.Append(' ');
            }
            return res.ToString().Trim(); 
        }