找出从S到T的词汇学增加的字符串序列中位于中间的字符串
- 最后更新 : 2021年8月6日
给定两个字符串 S和T,S在词法上大于T,任务是生成一个从S到T的词法递增的字符串序列( 均包括在内 ),并打印该序列中间的字符串。
**注意:**在词法递增的序列中总是有一个奇数的字符串。
例子。
**输入。**N = 2, S = "az", T = "bf"
输出。 "bc"
**解释。**字符串的递增序列是 "az", "ba", "bb", "bc", "bd", "be", "bf"。中间的字符串是 "bc"。输入。 S = "afogk", T = "asdji"
输出。 "alvuw"
办法。按 照下面的步骤来解决这个问题。
- 每一个字符串都可以在 基数26中用[0, 26]之间的整数来表示。
- 如果字符串代表两个整数 L和R,那么结果将是(L+R)/2,这将是一个中间数。
- 利用类似的概念,字符串可以用26进制的数字来表示
- 字符串如 "az "可以表示为(0 25)26,"bf "可以表示为(1 5)26;而""可以表示为()26
- 在将字符串转换为各自的基数26后,获得其 位相加.
- 从右到左迭代的位相加,并将余数结转到下一个位置。
- (0 25)26和(1 5)26的相加将是(2 4)26。
- 取每个位置的中间值并打印相应的字符。如果该位置是奇数,那么就把下一个位置移到26个字符。
举例说明。
S="afogk",T="asdji"
- S的26进制表示法=[0, 5, 14, 6, 10] 。
- T的26进制表示法=[0, 18, 3, 9, 8] 。
- 字符串S和T的相加=[0, 23, 17, 15, 18] 。
- (S+T)/2的中间字符串表示=[0, 11, 21, 20, 22]
- 因此,字符串中的每个字符将是基于0的'a'中的第a[i]个字符--索引
下面是上述方法的实现。
C++
// C++ Program for the above approach#include <bits/stdc++.h>using namespace std;// Function to print the string at// the middle of lexicographically// increasing sequence of strings from S to Tint printMiddleString(string S, string T,int N){// Stores the base 26 digits after additionvector<int> a1(N + 1);for (int i = 0; i < N; i++) {a1[i + 1] = S[i] -'a' + T[i] -'a';}// Iterete from right to left// and add carry to next positionfor (int i = N; i >= 1; i--) {a1[i - 1] += a1[i] / 26;a1[i] %= 26;}// Reduce the number to find the middle// string by dividing each position by 2for (int i = 0; i <= N; i++) {// If current value is odd,// carry 26 to the next index valueif (a1[i] & 1) {if (i + 1 <= N) {a1[i + 1] += 26;}}a1[i] /= 2;}for (int i = 1; i <= N; i++) {cout <<char(a1[i] +'a');}return 0;}// Driver Codeint main(){int N = 5;string S ="afogk";string T ="asdji";printMiddleString(S, T, N);} |
输出。
alvuw
时间复杂度。 O(N)
辅助空间。 O(N)
读者请注意!现在不要停止学习。掌握所有重要的DSA概念。 DSA自学课程以适合学生的价格获得所有重要的DSA概念,并成为行业的准备者。 要完成从学习语言到DS Algo以及更多的准备工作,请参考 完整的面试准备课程.
如果你想参加专家的现场课程 ,请参考 面向在职人士的DSA现场课程 和 面向学生的竞争性编程直播.
我的个人笔记 arrow_drop_up
保存