Two Characters

  • + 0 comments

    C#

    public static int alternate(string s)
        {
            int maxLength = 0;
            HashSet<char> uset = new HashSet<char>(s.ToCharArray());
            char[] chars = uset.ToArray();
            for (int i = 0; i < chars.Length; i++)
                for (int j = i+1; j < chars.Length; j++) {
                    int len = GetDuoCharsLength(s, chars[i], chars[j]);
                    if (len > maxLength) maxLength = len;
                }
                
            return maxLength;
        }
        
        private static int GetDuoCharsLength(string s, char ch1, char ch2) {
            if (s.IndexOf(ch1) > s.IndexOf(ch2)) {
                char temp = ch1;
                ch1 = ch2;
                ch2 = temp;
            }
            int len = 0;
            bool turn = true;
            foreach (char ch in s) {
                if (ch != ch1 && ch != ch2) continue;
                if ((turn && ch == ch1) || (!turn && ch == ch2)) {
                    turn = !turn;
                    len++;
                } else {
                    return 0;
                }
            }
            return len;
            
        }