Special String Again

  • + 0 comments

    I also attempted in c#, though mine might be more verbose.

    static long substrCount(int n, string s) {
    
        int specialSubstringCount = 0;
    
        for (int i = 0; i < n  ; i++ ){
            for (int j = i + 1; j < n; j++){
                 if(isSpecialSubstring(s.Substring(i, j - i + 1))){
                     specialSubstringCount += 1;
                     Console.WriteLine(specialSubstringCount);
                 }
            }            
        }
    
        return n + specialSubstringCount;
    }
    
    //check if its a special substring
    static bool isSpecialSubstring(string substring){
    
        //all characters are same
        bool allCharactersAreSame = true;
        StringBuilder builder = new StringBuilder(substring);
        Char currentCharacter = builder[0];     
        List<int> notSameIndexes = new List<int>();
        for (int i = 1 ; i < builder.Length; i++){
            if(builder[i] != currentCharacter){ 
                   allCharactersAreSame = false;
                   notSameIndexes.Add(i);         
            }
        }
    
         int midPoint = builder.Length / 2; 
        bool allCharactersExceptMiddleOneAreSame = notSameIndexes.Count() == 1 && notSameIndexes.First() == midPoint && builder.Length % 2 != 0;
    
    
        return allCharactersAreSame || allCharactersExceptMiddleOneAreSame;
    
        //all charaters except middle one are same
    
    }