菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
40
0

编程之美的2.17,数组循环移位 & 字符串逆转(反转) Hello world Welcome => Welcome world Hello

原创
05/13 14:22
阅读数 30030

代码如下:(类似于编程之美的2.17,数组循环移位)

 static void Main(string[] args)
        {

            string input = "Hello World Welcome";
            char[] tempArray = input.ToCharArray();          

            string result = RightShift(tempArray, 0, tempArray.Length-1);         
        }

        public static string RightShift(char[] arrary, int startIndex, int endIndex)
        {
            Reverse(arrary, 0, endIndex);

            startIndex = endIndex = 0;

            while (startIndex < arrary.Length - 1)
            {
                if (arrary[startIndex] == ' ')
                {
                    startIndex++;
                    endIndex++;
                    continue;

                }
                else if (arrary[endIndex] == ' ')
                {
                    int currentIndex = endIndex;
                    Reverse(arrary, startIndex, endIndex - 1);
                    startIndex = endIndex = currentIndex;
                }
                else if (endIndex == arrary.Length - 1)
                {
                    int currentIndex = endIndex;
                    Reverse(arrary, startIndex, endIndex);
                    startIndex = endIndex = currentIndex;
                }
                else
                {
                    endIndex++;
                }
            }

            StringBuilder builder = new StringBuilder();
            foreach (char item in arrary)
            {
                builder.Append(item);
            }

            return builder.ToString();

        }

        public static void Reverse(char[] arrary, int start, int end)
        {
            while (start < end)
            {
                char temp = arrary[start];
                arrary[start] = arrary[end];
                arrary[end] = temp;

                start++;
                end--;
            }
        }

 

 

 

发表评论

0/200
40 点赞
0 评论
收藏