从通过网络发送的数据包中解码消息
通过网络,消息作为数据包发送。每个数据包是一系列字节(8bits = 1 byte)。任务是解码长度为N的数据包 ( str )。数据包的格式如下:
- 数据包可以分成两部分。
- 第一个字节代表一个唯一值,比如K 。
- 数据包中剩余的字节代表要解码的消息。
- 每个消息字节都将与第一个字节进行异或运算,从而产生一组字母数字 ASCII字符以获取可读消息。
如果数据包的长度无效返回-1。
例子:
Input: str = “101010101110001011001111110001101100011011000101”, N = 48
Output: Hello
Explanation: Here K = 10101010, and the other bytes are:
“11100010”, “11001111”, “11000110”, “11000110”, “11000101”.
The Xor value with K are “01001000”, “01100101”, “01101100”, “01101100”, “01101111”
which have ASCII values 72, 101, 108, 108, 111 and the characters are ‘H’, ‘e’, ‘l’, ‘l’ and ‘o’.
Input: str = “1010101011100010111000101111”, N = 28
Output: -1
Explanation: The length of the packet is not valid. One byte of the message is missing some bits.
方法:问题的解决方案是基于执行。检查数据包长度的有效性。如果有效,则按照问题中的说明进行操作。请按照以下步骤操作:
- 检查输入长度是否可以被 8 整除,如果不是,则返回 -1。
- 现在,对于第一个字节,即前 8 位,计算十进制值并将其存储在一个变量中。
- 现在,对于每个即将到来的字节,将其与存储的第一个字节进行异或,并打印具有 ASCII 值的相应字符。
下面是上述方法的实现。
Java
// Java program to implement the approach
import java.util.*;
public class Main {
// Function to decode the message
static String decode(String str, int N)
{
// If length of packet is invalid
if (N % 8 != 0)
return "-1";
String res = "";
int j = 0, k = 0, first = 0, K = 0;
for (int i = 0; i < N; i++) {
k++;
// If one byte length is reached
if (k == 8) {
k = 0;
String s
= str.substring(j, i + 1);
int n
= Integer.parseInt(s, 2);
j = i + 1;
// If not the first byte add
// character to decoded message
if (first == 1) {
int z = n ^ K;
char ch = (char)z;
res += ch;
}
// If it is the first byte
else if (first == 0) {
first = 1;
K = n;
}
}
}
return res;
}
// Driver code
public static void main(String[] args)
{
String str = "101010101110001011001111110001101100011011000101";
int N = 48;
String ans = decode(str, N);
System.out.println(ans);
}
}
Python3
# Python code for the above approach
# Function to decode the message
def decode(strr: str, N: int) -> str:
# If length of packet is invalid
if N % 8 != 0:
return "-1"
res = ""
j, k, first, K = 0, 0, 0, 0
for i in range(N):
k += 1
# If one byte length is reached
if k == 8:
k = 0
s = strr[j : i + 1]
n = int(s, 2)
j = i + 1
# If not the first byte add
# character to decoded message
if first == 1:
z = n ^ K
ch = chr(z)
res += ch
# If it is the first byte
elif first == 0:
first = 1
K = n
return res
# Driver code
if __name__ == "__main__":
strr = "101010101110001011001111110001101100011011000101"
N = 48
ans = decode(strr, N)
print(ans)
# This code is contributed by N SaiSuprabhanu
Javascript
Hello
时间复杂度: O(N)
辅助空间: O(logN)