Menu

Hackerrank > Algorithms > Strings > Two Characters

January 7, 2017 - Hackerrank

Language: C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{

    static void Main(String[] args)
    {
        int len = Convert.ToInt32(Console.ReadLine());
        string s = Console.ReadLine();

        int longestSolution = 0;
        for (int i = 0; i < 26; i++)
        {
            for (int j = i + 1; j < 26; j++)
            {
                char c1 = (char)((int)'a' + i);
                char c2 = (char)((int)'a' + j);

                int currentChar = -1;
                int countChar = 0;
                for (int z = 0; z < len; z++)
                {
                    if (s[z] == c1)
                    {
                        if (currentChar == 1)
                        {
                            currentChar = -1;
                            break;
                        }
                        currentChar = 1;
                        countChar++;
                    }
                    else if (s[z] == c2)
                    {
                        if (currentChar == 2)
                        {
                            currentChar = -1;
                            break;
                        }
                        currentChar = 2;
                        countChar++;
                    }
                }

                if (currentChar != -1 &&
                    countChar > 1 &&
                    countChar > longestSolution)
                {
                    longestSolution = countChar;
                }
            }
        }
        Console.WriteLine(longestSolution);
    }
}

(663)

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on VK

Author of this post : Unknown Author

3 thoughts on “Hackerrank > Algorithms > Strings > Two Characters

bhakyalashmi

can u solve this problem in c or c++..?

Reply
    safrastyan

    Hi. Thank you for the comment.
    Generally we do not rewrite out solutions, we only accept requests that ask us to solve an already unsolved task, however if you have some questions about certain pieces of the code that you don’t understand feel free to ask (also in competitive programming sphere Java and C++ code are really very similar 🙂 ) .

    Reply
Caniberous

Could you provide a step by step explanation of this solution?

Reply

Leave a Reply

Your email address will not be published. Required fields are marked *