The idea is checking if string S is having an odd element or event. If it's an even then we should return -1. Then we start comparing every char from the middle to the start index and to the end of the string char index. if we find a different char the return -1. If not the we return index of middle char of the string.
Java Solution :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public static int strSymPoint(String S) { if(S.length() == 0 || S.length()%2 == 0) return -1; int toStart = (S.length()/2)-1; int toEnd = (S.length()/2)+1; while(toStart >= 0) { if(S.charAt(toStart) != S.charAt(toEnd)) return -1; toStart -= 1; toEnd += 1; } return S.length()/2; } |
Result :
C# solution :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public static int strSymPoint(string S) { if (S.Length == 0 || S.Length % 2 == 0) return -1; int toStart = (S.Length / 2) - 1; int toEnd = (S.Length / 2) + 1; while (toStart >= 0) { if (S[toStart]!= S[toEnd]) return -1; toStart -= 1; toEnd += 1; } return S.Length / 2; } |
Result :
No comments:
Post a Comment