📌  相关文章
📜  通过给定的操作从给定的加密字符串中还原原始字符串

📅  最后修改于: 2021-04-24 19:04:22             🧑  作者: Mango

给定字符串str和正整数N ,任务是反转N个字符并跳过N个字符,直到字符串的末尾以生成加密消息。

例子:

方法:请按照以下步骤解决问题:

  • 遍历给定的字符串。
  • 将迭代器增加2 *N
  • 逐步反转N个字符。

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
 
// Function to decrypt and print the
// original strings
int decryptString(string s, unsigned int N)
{
 
    for (unsigned int i = 0; i < s.size();
         i += 2 * N) {
        auto end = s.begin() + i + N;
     
 
        // If length is exceeded
        if (i + N > s.size())
            end = s.end();
 
        // Reverse the string
        reverse(s.begin() + i, end);
           
       
    }
 
    cout << s << endl;
}
 
// Driver Code
int main()
{
    string s = "ihTs suohld  ebeas!y";
    unsigned int N = 3;
    decryptString(s, N);
 
    return 0;
}


Python3
# Python3 program to implement
# the above approach
 
# Function to decrypt and print the
# original strings
def decryptString(s, N):
     
    for i in range(0, len(s), 2 * N):
        if (i + N < len(s)):
            end = s[i + N]
             
        # If length is exceeded
        if (i + N > len(s)):
            end = s[-1]
 
        # Reverse the string
        if (i == 0):
            s = s[i + N - 1::-1] + s[i + N:]
        else:
            s = s[:i] + s[i + N - 1:i - 1:-1] + s[i + N:]
 
    print(s)
 
# Driver Code
if __name__ == "__main__":
 
    s = "ihTs suohld  ebeas!y"
    N = 3
     
    decryptString(s, N)
 
# This code is contributed by ukasp


输出:
This should be easy!

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