这个题目面试的时候,用的是最简单,但多开辟内存的方法,后来自己想想,在原数组进行操作的方法:
private static string GreaterLeftLessRight(string str, char c){char[] array = str.ToCharArray();int comparingIndex = str.IndexOf(c);int i = 0;int j = comparingIndex + 1;int lastExchangePositionInLeft = -1;int lastExchangePositionInRight = -1;int rightestIndex = comparingIndex;char tmp;while (i < comparingIndex || j < array.Length){int shouldExchangeInLeft = -1;int shouldExchangeInRight = -1;while (i < comparingIndex){if (array[i] < c){shouldExchangeInLeft = i;i++;break;}else{i++;}}while (j < array.Length){if (array[j] >= c){shouldExchangeInRight = j;j++;break;}else{j++;}}if (shouldExchangeInLeft != -1 && shouldExchangeInRight != -1 && array[shouldExchangeInRight] != c){ExchangeCharacterInArray(array, shouldExchangeInLeft, shouldExchangeInRight);lastExchangePositionInLeft = shouldExchangeInLeft;lastExchangePositionInRight = shouldExchangeInRight;}else if (shouldExchangeInLeft != -1 && shouldExchangeInRight == -1){tmp = array[shouldExchangeInLeft];int moveEndIndex = lastExchangePositionInRight == -1 ? array.Length - 1 : lastExchangePositionInRight;MoveCharacterInArray(array, shouldExchangeInLeft, moveEndIndex, tmp);i--;comparingIndex--;}else if (shouldExchangeInLeft != -1 && array[shouldExchangeInRight] == c){array[shouldExchangeInRight] = array[shouldExchangeInLeft];MoveCharacterInArray(array, shouldExchangeInLeft, rightestIndex, c);i--;comparingIndex--;}else if (shouldExchangeInLeft == -1 && shouldExchangeInRight != -1 && array[shouldExchangeInRight] != c){tmp = array[shouldExchangeInRight];MoveCharacterInArray(array, shouldExchangeInRight, comparingIndex, tmp);comparingIndex++;rightestIndex = comparingIndex;}else if (shouldExchangeInLeft == -1 && shouldExchangeInRight != -1 && array[shouldExchangeInRight] == c){int moveEndIndex = rightestIndex + 1;MoveCharacterInArray(array, shouldExchangeInRight, moveEndIndex, c);rightestIndex = moveEndIndex;}}return new string(array);}private static void MoveCharacterInArray(char[] array, int startIndex, int endIndex, char endCharacter){if (startIndex == endIndex){return;}else if (startIndex < endIndex){for (int k = startIndex; k < endIndex; k++){array[k] = array[k + 1];}array[endIndex] = endCharacter;}else{for (int k = startIndex; k > endIndex; k--){array[k] = array[k - 1];}array[endIndex] = endCharacter;}}private static void ExchangeCharacterInArray(char[] array, int leftPosition, int rightPosition){char tmp = array[leftPosition];array[leftPosition] = array[rightPosition];array[rightPosition] = tmp;}