📜  通过将给定字符串的字符按第二个字符串的相应索引处存在的数字递增来生成字符串

📅  最后修改于: 2022-05-13 01:56:05.314000             🧑  作者: Mango

通过将给定字符串的字符按第二个字符串的相应索引处存在的数字递增来生成字符串

给定两个大小相同的字符串S[]N[] ,任务是通过添加相应索引的字符串N[]的数字来更新字符串S[]

例子:

方法:想法是从左到右遍历字符串S[] 。获取字符串N[]的 ASCII 值并将其添加到字符串S[]的 ASCII 值中。如果值超过122 ,这是最后一个字母'z'的 ASCII 值。然后将该值减去26 ,即英文字母的总数。用获得的 ASCII 值的字符更新字符串S。请按照以下步骤解决问题:

  • 使用变量i遍历范围[0, S.size())并执行以下任务:
    • 将变量ab初始化为N[i]S[i] 的整数和 ascii 值。
    • 如果b大于122 ,则从b 中减去26
    • S[i]设置为char(b)。
  • 执行上述步骤后,打印S[]的值作为答案。

下面是上述方法的实现。

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to update string
string updateStr(string S, string N)
{
    for (int i = 0; i < S.size(); i++) {
 
        // Get ASCII value
        int a = int(N[i]) - '0';
        int b = int(S[i]) + a;
 
        if (b > 122)
            b -= 26;
 
        S[i] = char(b);
    }
    return S;
}
 
// Driver Code
int main()
{
    string S = "sun";
    string N = "966";
    cout << updateStr(S, N);
    return 0;
}


Java
// Java code to implement above approach
import java.util.*;
public class GFG {
 
  // Function to update string
  static String updateStr(String S, String N)
  {
    String t = "";
    for (int i = 0; i < S.length(); i++) {
 
      // Get ASCII value
      int a = (int)(N.charAt(i) - '0');
      int b = (int)(S.charAt(i) + a);
 
      if (b > 122)
        b -= 26;
 
      char x = (char)b;
      t +=x;
    }
    return t;
  }
 
  // Driver code
  public static void main(String args[])
  {
    String S = "sun";
    String N = "966";
    System.out.println(updateStr(S, N));
 
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Python3
# Python code for the above approach
 
# Function to update string
def updateStr(S, N):
    S = list(S)
    for i in range(len(S)):
 
        # Get ASCII value
        a = ord(N[i]) - ord('0')
        b = ord(S[i]) + a
 
        if (b > 122):
            b -= 26
 
        S[i] = chr(b)
    return "".join(S)
 
# Driver Code
 
S = "sun"
N = "966"
print(updateStr(S, N))
 
# This code is contributed by Saurabh Jaiswal


C#
// C# code to implement above approach
using System;
public class GFG {
 
  // Function to update string
  static String updateStr(String S, String N)
  {
    String t = "";
    for (int i = 0; i < S.Length; i++) {
 
      // Get ASCII value
      int a = (int)(N[i] - '0');
      int b = (int)(S[i] + a);
 
      if (b > 122)
        b -= 26;
 
      char x = (char)b;
      t +=x;
    }
    return t;
  }
 
  // Driver code
  public static void Main(String []args)
  {
    String S = "sun";
    String N = "966";
    Console.WriteLine(updateStr(S, N));
 
  }
}
 
// This code is contributed by shikhasingrajput


Javascript


输出
bat

时间复杂度: O(|S|)
辅助空间: O(1)