Monday, 28 January 2019

String Topics in C#

Write a Program which checks if two Strings are Anagram or not?

using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;

class Solution
{

    // Complete the makeAnagram function below.
    static string makeAnagram(string a, string b)
    {
        char[] char1 = a.ToLower().ToCharArray();
        char[] char2 = b.ToLower().ToCharArray();
        Array.Sort(char1);
        Array.Sort(char2);
        string NewWord1 = new string(char1);
        string NewWord2 = new string(char2);

        if (NewWord1 == NewWord2)
        {
            return ("Anagrams");
        }
        else
        {
            return ("Not Anagrams");
        }
    }

    static void Main(string[] args)
    {
       // TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
        Console.Write("Enter first word:");
        string a = Console.ReadLine();
        Console.Write("Enter second word:");
        string b = Console.ReadLine();

        string res = makeAnagram(a, b);
        Console.WriteLine(res);
        Console.ReadLine();

        //textWriter.WriteLine(res);

        //textWriter.Flush();
        //textWriter.Close();
    }
}

Write a Program to make two Strings are Anagram.
Alice is taking a cryptography class and finding anagrams to be very useful. We consider two strings to be anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency For example, bacdc and dcbac are anagrams, but bacdc and dcbad are not.
Alice decides on an encryption scheme involving two large strings where encryption is dependent on the minimum number of character deletions required to make the two strings anagrams. Can you help her find this number?
Given two strings,  and , that may or may not be of the same length, determine the minimum number of character deletions required to make  and  anagrams. Any characters can be deleted from either of the strings.
For example, if  and , we can delete  from string  and  from string  so that both remaining strings are and  which are anagrams.
Function Description
Complete the makeAnagram function in the editor below. It must return an integer representing the minimum total characters that must be deleted to make the strings anagrams.
makeAnagram has the following parameter(s):
·       a: a string
·       b: a string
Input Format
The first line contains a single string, .
The second line contains a single string, .
Constraints
·       The strings  and  consist of lowercase English alphabetic letters ascii[a-z].
Output Format
Print a single integer denoting the number of characters you must delete to make the two strings anagrams of each other.
Sample Input
cde
abc
Sample Output
4
Explanation
We delete the following characters from our two strings to turn them into anagrams of each other:
1.     Remove d and e from cde to get c.
2.     Remove a and b from abc to get c.
We must delete  characters to make both strings anagrams, so we print  on a new line.

using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;

class Solution {

    // Complete the makeAnagram function below.
    static int makeAnagram(string a, string b)
    {
        char[] aO = a.Trim().Replace(" """).ToLower().ToCharArray();
        Array.Sort(aO);
 
        char[] bO = b.Trim().Replace(" """).ToLower().ToCharArray();
        Array.Sort(bO);
 
 
        ArrayList aOrignal = new ArrayList();
        aOrignal.AddRange(aO);
 
        ArrayList bOrignal = new ArrayList();
        bOrignal.AddRange(bO);
 
        Dictionary<charint> aDic = new Dictionary<charint>();
        foreach (char item in aOrignal)
        {
 
            if (aDic.ContainsKey(item))
                aDic[item]++;
            else
                aDic.Add(item, 1);
        }
 
 
        Dictionary<charint> bDic = new Dictionary<charint>();
        foreach (char item in bOrignal)
        {
            if (bDic.ContainsKey(item))
                bDic[item]++;
            else
                bDic.Add(item, 1);
        }
 
        foreach (KeyValuePair<charint> kvp in aDic.ToList())
        {
            if (aOrignal.Contains(kvp.Key) && bOrignal.Contains(kvp.Key))
            {
                aDic[kvp.Key] -= 1;
                bDic[kvp.Key] -= 1;
                for (var i = 1; i < kvp.Value; i++)
                {
                    if (aDic.ContainsKey(kvp.Key) && bDic.ContainsKey(kvp.Key))
                    {
                        if (aDic[kvp.Key] > 0 && bDic[kvp.Key] > 0)
                        {
                            aDic[kvp.Key] -= 1;
                            bDic[kvp.Key] -= 1;
                        }
                    }
                }
 
 
 
            }
 
 
        }
        int count = 0;
        foreach (KeyValuePair<charint> kvp in bDic)
        {
            count += kvp.Value;
 
 
        }
        foreach (KeyValuePair<charint> kvp in aDic)
        {
            count += kvp.Value;
 
 
        }
 
        return (count);
 
    }

    static void Main(string[] args) {
        TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

        string a = Console.ReadLine();

        string b = Console.ReadLine();

        int res = makeAnagram(a, b);

        textWriter.WriteLine(res);

        textWriter.Flush();
        textWriter.Close();
    }
}

Alternating Characters
You are given a string containing characters  and  only. Your task is to change it into a string such that there are no matching adjacent characters. To do this, you are allowed to delete zero or more characters in the string.
Your task is to find the minimum number of required deletions.
For example, given the string , remove an  at positions  and  to make  in  deletions.
Function Description
Complete the alternatingCharacters function in the editor below. It must return an integer representing the minimum number of deletions to make the alternating string.
alternatingCharacters has the following parameter(s):
·       s: a string
Input Format
The first line contains an integer , the number of queries.
The next  lines each contain a string .
Constraints
·       Each string  will consist only of characters  and 
Output Format
For each query, print the minimum number of deletions required on a new line.
Sample Input
5
AAAA
BBBBB
ABABABAB
BABABA
AAABBB
Sample Output
3
4
0
0
4
Explanation
The characters marked red are the ones that can be deleted so that the string doesn't have matching consecutive characters.
AAAA ->A (3 deletions)
BBBBB -> B (4 deletions)
ABABABAB -> (0 deletion)
BABABA -> BABABA (0 deletion)
AAABBB -> AB (4 deletion)

The problem is pretty simple. One straight forward solution can be given as follows.
If there are N consecutive same character delete N-1 out of those N characters.
Which will result into a string, in which no two consecutive characters will be the same. See the implement of the setter for the more details.

using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;

class Solution
{

    // Complete the alternatingCharacters function below.
    static int alternatingCharacters(string s)
    {
        string str = s;
            int ans = 0;
            for (int i = 0; i < s.Length - 1; i++)
            {
                if (str[i] == str[i + 1]) // If two consecutive characters are the same, delete one of them.
                    ans++;
            }

        return ans;

    }

    static void Main(string[] args)
    {
        //TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

        Console.WriteLine("Enter a number you want to test :");

        int q = Convert.ToInt32(Console.ReadLine());


        for (int qItr = 0; qItr < q; qItr++)
        {
            Console.WriteLine("Enter the string:");
            string s = Console.ReadLine();

            int result = alternatingCharacters(s);
            Console.WriteLine("The no character need to delete is :" + result);

           // textWriter.WriteLine(result);
        }
        Console.ReadLine();

        //textWriter.Flush();
        //textWriter.Close();
    }
}

Sherlock and the Valid String

Sherlock considers a string to be valid if all characters of the string appear the same number of times. It is also valid if he can remove just  character at  index in the string, and the remaining characters will occur the same number of times. Given a string , determine if it is valid. If so, return YES, otherwise return NO.
For example, if , it is a valid string because frequencies are . So is  because we can remove one  and have  of each character in the remaining string. If  however, the string is not valid as we can only remove  occurrence of . That would leave character frequencies of .
Function Description
Complete the isValid function in the editor below. It should return either the string YES or the string NO.
isValid has the following parameter(s):
·       s: a string
Input Format
A single string .
Constraints
·       Each character 
Output Format
Print YES if string  is valid, otherwise, print NO.
Sample Input 0
aabbcd
Sample Output 0
NO
Explanation 0
Given , we would need to remove two characters, both c and d  aabb or a and b  abcd, to make it valid. We are limited to removing only one character, so  is invalid.
Sample Input 1
aabbccddeefghi
Sample Output 1
NO
Explanation 1
Frequency counts for the letters are as follows:
{'a': 2, 'b': 2, 'c': 2, 'd': 2, 'e': 2, 'f': 1, 'g': 1, 'h': 1, 'i': 1}
There are two ways to make the valid string:
·       Remove  characters with a frequency of : .
·       Remove  characters of frequency : .
Neither of these is an option.
Sample Input 2
abcdefghhgfedecba
Sample Output 2
YES
Explanation 2
All characters occur twice except for  which occurs  times. We can delete one instance of  to have a valid string.
Solution
The problem domain only encompasses the ascii chars a-z so this is easy we just keep track of the occurences of the letters and then check if more than one character occurs a different number of times than the rest. The implementation is straight forward and just requires counting and then checking if the conditions apply to the resulting count.
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;

class Solution
{

    // Complete the isValid function below.
    static string isValid(string s)
    {
        string str=s;
        int[] a = new int[26];
        int temp=0;
        int i = 0;
        
        for(int j=0;j<str.Length; j++)
        {
            a[str[j] - 97]++;
        }

        for (i = 0; i < 26; i++)
        {
            if (a[i] != 0)
            {
                temp = a[i];
                break;
            }
        }
        int flag = -1;
        for (i = 0; i < 26; i++)
        {
            if (a[i] != 0)
            {
                if (temp - a[i] == 1)
                {
                    if (flag == -1)
                    {
                        flag = 0;
                    }
                    else
                    {
                        flag = 1;
                    }
                    if (a[i] != 1)
                    {
                        temp = a[i];
                    }
                }
                else if (a[i] - temp == 1)
                {
                    if (flag == -1)
                    {
                        flag = 0;
                    }
                    else
                    {
                        flag = 1;
                    }
                    if (a[i] != 1)
                    {
                        temp = a[i];
                    }
                }
                else if (Math.Abs(temp - a[i]) > 1)
                {
                    if (flag == -1)
                    {
                        flag = 0;
                        continue;
                    }
                    flag = 2;
                    break;
                }
            }
        }
        if (flag == -1 || flag == 0)
        {
            return("YES");
        }
        else
        {
            return("NO");
        }
        
    }

    static void Main(string[] args)
    {
        //TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

        string s = Console.ReadLine();

        string result = isValid(s);
        Console.WriteLine("Result" + result);
        Console.ReadLine();

        //textWriter.WriteLine(result);

        //textWriter.Flush();
        //textWriter.Close();
    }
}

Special Palindrome


A string is said to be a special palindromic string if either of two conditions is met:
·       All of the characters are the same, e.g. aaa.
·       All characters except the middle one are the same, e.g. aadaa.
special palindromic substring is any substring of a string which meets one of those criteria. Given a string, determine how many special palindromic substrings can be formed from it.
For example, given the string s=mnonopoo , we have the following special palindromic substrings:.
{m,n,o,n,o,p,o,o,non,ono,opo,oo}
Function Description
Complete the substrCount function in the editor below. It should return an integer representing the number of special palindromic substrings that can be formed from the given string.
substrCount has the following parameter(s):
·       n: an integer, the length of string s
·       s: a string
Input Format
The first line contains an integer, , the length of .
The second line contains the string .
Constraints

Each character of the string is a lowercase alphabet, .
Output Format
Print a single line containing the count of total special palindromic substrings.
Sample Input 0
5
asasd
Sample Output 0
7
Explanation 0
The special palindromic substrings of  s=asasd are {a,s,a,s,d,asa,sas}
Sample Input 1
7
abcbaba
Sample Output 1
10
Explanation 1
The special palindromic substrings of  s=abcbaba are {},a,b,c,b,a,b,a,bcb,bab,aba
Sample Input 2
4
aaaa
Sample Output 2
10
Explanation 2
The special palindromic substrings of s=aaaa are {a,a,a,a,aa,aa,aa,aaa,aaa,aaaa}
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;

class Solution
{

    // Complete the substrCount function below.
    static long substrCount(int n, string s)
    {
        int no = s.Length;

        // store count of special 
        // Palindromic substring 
        int result = 0;

        // it will store the count  
        // of continues same char 
        int[] sameChar = new int[no];
        for (int v = 0; v < no; v++)
            sameChar[v] = 0;

        int i = 0;

        // traverse string character 
        // from left to right 
        while (i < no)
        {

            // store same character count 
            int sameCharCount = 1;

            int j = i + 1;

            // count smiler character 
            while (j < no &&
                   s[i] == s[j])
            {
                sameCharCount++;
                j++;
            }

            // Case : 1 
            // so total number of  
            // substring that we can 
            // generate are : K *( K + 1 ) / 2 
            // here K is sameCharCount 
            result += (sameCharCount *
                      (sameCharCount + 1) / 2);

            // store current same char  
            // count in sameChar[] array 
            sameChar[i] = sameCharCount;

            // increment i 
            i = j;
        }

        // Case 2: Count all odd length 
        //         Special Palindromic 
        //         substring 
        for (int j = 1; j < no; j++)
        {
            // if current character is  
            // equal to previous one  
            // then we assign Previous  
            // same character count to 
            // current one 
            if (s[j] == s[j - 1])
                sameChar[j] = sameChar[j - 1];

            // case 2: odd length 
            if (j > 0 && j < (no - 1) &&
               (s[j - 1] == s[j + 1] &&
                s[j] != s[j - 1]))
                result += Math.Min(sameChar[j - 1],
                                  sameChar[j + 1]);
        }

        // subtract all single  
        // length substring 

        return result;
       // return result - no;


    }

    static void Main(string[] args)
    {
        // TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
        Console.WriteLine("Enter a number");
        int n = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter a special string for palidrom count");
        string s = Console.ReadLine();

        long result = substrCount(n, s);

        Console.WriteLine(result);
        Console.ReadLine();

        //textWriter.WriteLine(result);

        //textWriter.Flush();
        //textWriter.Close();
    }
}