考虑到输入的样子了,我估计编码发生这样的事情:使用此代码
// The used length should be 3;
String encode(String input, int length) {
String output = "";
for(int i = 0;i<input.length();++i) {
output += input.subSequence(i, i+length);
if(i+length== input.length()) break;
}
return output;
}
,所需的编码是一样的,你必须解码编码后String
。
使用相同的机制,解码可能发生这样的:
static String decode(String input, int length) {
String output = "";
for(int i = 0;i<input.length();i+=length) {
output +=input.charAt(i);
if(i+length>=input.length())
output += input.substring(i+1);
}
return output;
}
给定一个小程序,代码可以解码和编码给定的String
:
public static void main(String[] args) {
String s1 = "REAL STEEL";
String encoded = encode(s1, 3);
System.out.println("Encoded the original " + s1 + " to be " + encoded);
System.out.println("Decoded again to: " + decode(encoded,3));
}
static String encode(String input, int length) {
String output = "";
for(int i = 0;i<input.length();++i) {
output += input.subSequence(i, i+length);
if(i+length== input.length()) break;
}
return output;
}
static String decode(String input, int length) {
String output = "";
for(int i = 0;i<input.length();i+=length) {
output +=input.charAt(i);
if(i+length>=input.length())
// Whenever the end was reached, the repeating has stopped
// Here it just adds to the end of the output what is left.
output += input.substring(i+1);
}
return output;
}
O/P
Encoded the original REAL STEEL to be REAEALAL L S STSTETEEEEL
Decoded again to: REAL STEEL
与您的代码的区别是,它不严格使用fi前两个字符与编码相同,但是在编码结束时(尽管重新编码),它确实注意到了这一点。在这种情况下,它只是将缺少的字母添加到解码输出的末尾。
你知道哪些测试用例没有通过吗?因为从案件的案件能正常运行所以 –
即使我不能理解案件!代码给出了正确的输出...... @Vlad – utkdub
@ dutaravi12345只是因为一个测试用例是有效的,并不意味着它完全有效。但是考虑到问题内的输入,我觉得解码应该以不同的方式发生。 – SomeJavaGuy