2016-12-28 45 views
-1

这是一个问题:查询来解决:WhatsApp的组

一个WhatsApp的组中的一组朋友共享消息的。由于他们的想法被黑客攻击的风险很高,他们形成了一种共享文本消息的新方法,这对于骇客/查看这些消息的人来说是混乱的。现在你的任务是为黑客创建一个程序来解决他在解码消息时遇到的问题 。样品输入:REAEALAL大号小号 STSTETEEEEL输出:REAL STEEL

这是我已经制定了到现在为止:

import java.util.*; 
class hide 
{ 
    public static void main(String args[]) 
    { 
     Scanner sc=new Scanner(System.in); 
     String a=sc.nextLine(); 
     String b=a.substring(0,2); 
     int n=a.length(); 
     for(int i=0;i<n-2;i++) 
     { 
      if(a.charAt(i)!=a.charAt(i+2)) 
      b=b+a.charAt(i+2); 
     } 
     System.out.print(b.trim()); 
    } 
} 

但它不是通过测试的情况下?

+0

你知道哪些测试用例没有通过吗?因为从案件的案件能正常运行所以 –

+0

即使我不能理解案件!代码给出了正确的输出...... @Vlad – utkdub

+0

@ dutaravi12345只是因为一个测试用例是有效的,并不意味着它完全有效。但是考虑到问题内的输入,我觉得解码应该以不同的方式发生。 – SomeJavaGuy

回答

1

考虑到输入的样子了,我估计编码发生这样的事情:使用此代码

// 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前两个字符与编码相同,但是在编码结束时(尽管重新编码),它确实注意到了这一点。在这种情况下,它只是将缺少的字母添加到解码输出的末尾。