Find the Mid-Alphabet for each index of the given Pair of Strings
Last Updated :
29 Dec, 2022
Given two same-length strings str1 and str2 consisting of lowercase English alphabets, the task is to find the Mid-Alphabet for each index of the given pair of Strings.
Examples:
Input: str1 = “abcd”, str2 = “cdef”
Output: bcde
Explanation:
b is mid of a and c
c is mid of b and d
d is mid of c and e
e is mid of e and f
Input: str1 = “akzbqzgw”, str2 = “efhctcsz”
Output: chqbrnmx
Approach:
The Mid-Alphabet can be calculated by taking an average of the ASCII values of the characters in each string at that index.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findMidAlphabet(string s1, string s2, int n)
{
for ( int i = 0; i < n; i++) {
int mid = (s1[i] + s2[i]) / 2;
cout << ( char )mid;
}
}
int main()
{
string s1 = "akzbqzgw" ;
string s2 = "efhctcsz" ;
int n = s1.length();
findMidAlphabet(s1, s2, n);
return 0;
}
|
Java
class GFG
{
static void findMidAlphabet(String s1,
String s2, int n)
{
for ( int i = 0 ; i < n; i++)
{
int mid = (s1.charAt(i) +
s2.charAt(i)) / 2 ;
System.out.print(( char )mid);
}
}
public static void main(String []args)
{
String s1 = "akzbqzgw" ;
String s2 = "efhctcsz" ;
int n = s1.length();
findMidAlphabet(s1, s2, n);
}
}
|
Python3
def findMidAlphabet(s1, s2, n):
for i in range (n):
mid = ( ord (s1[i]) + ord (s2[i])) / / 2
print ( chr (mid), end = "")
s1 = "akzbqzgw"
s2 = "efhctcsz"
n = len (s1)
findMidAlphabet(s1, s2, n)
|
C#
using System;
public class GFG
{
static void findMidAlphabet(String s1,
String s2, int n)
{
for ( int i = 0; i < n; i++)
{
int mid = (s1[i] +
s2[i]) / 2;
Console.Write(( char )mid);
}
}
public static void Main(String []args)
{
String s1 = "akzbqzgw" ;
String s2 = "efhctcsz" ;
int n = s1.Length;
findMidAlphabet(s1, s2, n);
}
}
|
Javascript
<script>
function findMidAlphabet(s1, s2, n)
{
for ( var i = 0; i < n; i++)
{
var mid = (s1[i].charCodeAt(0) +
s2[i].charCodeAt(0)) / 2;
document.write(String.fromCharCode(mid));
}
}
var s1 = "akzbqzgw" ;
var s2 = "efhctcsz" ;
var n = s1.length;
findMidAlphabet(s1, s2, n);
</script>
|
Time Complexity: , where N is the length of the String.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...