C # algorithm to determine whether a string is a symmetric string,
I remember that during an interview, the interviewer gave me a computer and asked me to write an algorithm on-site to determine whether a string is a symmetric string. I used a few minutes to write a very simple code.
The symmetric string here refers to the character order on the left and right of the string, such as "abba". A single string is an asymmetric string for the time being, although some strings seem symmetric, such as "A," H "," O "," medium "," people "..., strictly speaking, they are also asymmetrical. When they are enlarged, the line width is different.
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;}
This is very simple. It can traverse up to half the length of a string, compare the first and last, and the second and last...
The function is implemented, but it is too simple and inefficient. Since it is an algorithm, it requires high efficiency.
I discussed it with my friends, and they gave me another solution.
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); }
This solution is to split the string into two halves and reverse the last half to compare it.
The results can also be achieved without traversing. It seems higher than the previous solution, and the actual operation efficiency is lower.
These two solutions are only entry-level and certainly have better and more efficient writing methods. Please share them with us. Thank you!
If it is helpful to you, please give me a thumbs up. Thank you!
For deficiencies and errors, please criticize and correct them!