From 6865c7a2389c9f90c281576eb98b53e89aac3d74 Mon Sep 17 00:00:00 2001 From: Ivandro Ismael Date: Thu, 24 Nov 2016 18:05:57 +0000 Subject: [PATCH] [Utilities] - Optimize ReverseParenthesis. --- libse/Utilities.cs | 40 +++++++++++++++++++++++++++++----------- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/libse/Utilities.cs b/libse/Utilities.cs index f54e9c3a4..b60d348f5 100644 --- a/libse/Utilities.cs +++ b/libse/Utilities.cs @@ -1218,17 +1218,35 @@ namespace Nikse.SubtitleEdit.Core private static string ReverseParenthesis(string s) { - const string k = "@__<<>___@"; - - s = s.Replace("(", k); - s = s.Replace(')', '('); - s = s.Replace(k, ")"); - - s = s.Replace("[", k); - s = s.Replace(']', '['); - s = s.Replace(k, "]"); - - return s; + if (string.IsNullOrEmpty(s)) + { + return s; + } + int len = s.Length; + char[] chars = new char[len]; + // O(n) + for (int i = len - 1; i >= 0; i--) + { + char ch = s[i]; + if (ch == '(') + { + ch = ')'; + } + else if (ch == ')') + { + ch = '('; + } + else if (ch == '[') + { + ch = ']'; + } + else if (ch == ']') + { + ch = '['; + } + chars[i] = ch; + } + return new string(chars); } public static string FixEnglishTextInRightToLeftLanguage(string text, string reverseChars)