static bool IsSymmetry1(string str) { if (string.IsNullOrEmpty(str) || str.Length == 1) { return false; } for (int i = 0; i < str.Length / 2; i++) { if (str[i] != str[str.Length - 1 - i]) { return false; } } return true; }
static bool IsSymmetry2(string str) { if (string.IsNullOrEmpty(str) || str.Length == 1) { return false; } var halfLength = str.Length/2; var str1 = str.Substring(0, halfLength); var str2 = new String(str.Substring(str.Length%2 == 0 ? halfLength : halfLength + 1, halfLength).Reverse().ToArray()); return str1.Equals(str2); }
效果也能实现,没用遍历,看起来比上个方案要高大上,实际运行效率更低。
时间: 2024-10-13 22:30:20