TopCoder SRMS 1 字符串处理问题 Java题解

Problem Statement

 
Let‘s say you have a binary string such as the following:

011100011

One way to encrypt this string is to add to each digit the sum of its adjacent digits. For example, the above string would become:

123210122

In particular, if P is the original string, and Q is the encrypted string, then
Q[i] = P[i-1] + P[i] + P[i+1] for all digit positions i. Characters off the left and right edges of the string are treated as zeroes.

An encrypted string given to you in this format can be decoded as follows (using
123210122 as an example):

  1. Assume P[0] = 0.
  2. Because Q[0] = P[0] + P[1] = 0 + P[1] = 1, we know that P[1] = 1.
  3. Because Q[1] = P[0] + P[1] + P[2] = 0 + 1 + P[2] = 2, we know that
    P[2] = 1
    .
  4. Because Q[2] = P[1] + P[2] + P[3] = 1 + 1 + P[3] = 3, we know that
    P[3] = 1
    .
  5. Repeating these steps gives us P[4] = 0, P[5] = 0, P[6] = 0,
    P[7] = 1, and P[8] = 1.
  6. We check our work by noting that Q[8] = P[7] + P[8] = 1 + 1 = 2. Since this equation works out, we are finished, and we have recovered one possible original string.

Now we repeat the process, assuming the opposite about P[0]:

  1. Assume P[0] = 1.
  2. Because Q[0] = P[0] + P[1] = 1 + P[1] = 1, we know that P[1] = 0.
  3. Because Q[1] = P[0] + P[1] + P[2] = 1 + 0 + P[2] = 2, we know that
    P[2] = 1
    .
  4. Now note that Q[2] = P[1] + P[2] + P[3] = 0 + 1 + P[3] = 3, which leads us to the conclusion that
    P[3] = 2. However, this violates the fact that each character in the original string must be ‘0‘ or ‘1‘. Therefore, there exists no such original string
    P where the first digit is ‘1‘.

Note that this algorithm produces at most two decodings for any given encrypted string. There can never be more than one possible way to decode a string once the first binary digit is set.

Given a String message, containing the encrypted string, return a String[] with exactly two elements. The first element should contain the decrypted string assuming the first character is ‘0‘; the second element should assume the first character
is ‘1‘. If one of the tests fails, return the string "NONE" in its place. For the above example, you should return
{"011100011", "NONE"}.

Definition

 
Class: BinaryCode
Method: decode
Parameters: String
Returns: String[]
Method signature: String[] decode(String message)
(be sure your method is public)

Limits

 
Time limit (s): 2.000
Memory limit (MB): 64

Constraints

- message will contain between 1 and 50 characters, inclusive.
- Each character in message will be either ‘0‘, ‘1‘, ‘2‘, or ‘3‘.

Examples

0)  
 
"123210122"
Returns: { "011100011",  "NONE" }

The example from above.

1)  
 
"11"
Returns: { "01",  "10" }

We know that one of the digits must be ‘1‘, and the other must be ‘0‘. We return both cases.

2)  
 
"22111"
Returns: { "NONE",  "11001" }

Since the first digit of the encrypted string is ‘2‘, the first two digits of the original string must be ‘1‘. Our test fails when we try to assume that
P[0] = 0.

3)  
 
"123210120"
Returns: { "NONE",  "NONE" }

This is the same as the first example, but the rightmost digit has been changed to something inconsistent with the rest of the original string. No solutions are possible.

4)  
 
"3"
Returns: { "NONE",  "NONE" }
 
5)  
 
"12221112222221112221111111112221111"
Returns:
{ "01101001101101001101001001001101001",
  "10110010110110010110010010010110010" }
 

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved.

计算有多少种解密字符串,因为是01串,故此只能最多有两种了。

才第二次使用Java解题,会不会像是披着Java外壳的C++程序呢?

实际体会:

C++转Java倒真的不难,最大的难点就是要知道如何使用Java的一些函数,比如本题的string处理,如果使用C++自然是直接加或者使用VC的直接push_back,不过Java好像有个什么StringBuilder类,这里我直接+=接起来了。

故此C++转Java的问题实际上是记忆问题,不存在理解问题了,因为Java有的概念,C++差不多都有,理解障碍就没有了。

最后大家都熟悉的稍微有点争论的一个结论:只要熟悉一种语言,那么学其他语言就会很轻松了。

我个人是支持这个结论的。前提是要知道“熟悉”这两个字的分量。

看过两本C++经典书就说自己熟悉C++是不对的,就像看过算法导论就说自己懂算法也是不对的,需要大量的练习,思考,深刻地体会。

public class BinaryCode {

	private boolean equ(int a, int b) {
		return a == b;
	}

	public String[] decode(String ms) {
		String rs[] = new String[2];
		if (ms.isEmpty())
			return rs;

		rs[0] = getCode(ms, "0");
		rs[1] = getCode(ms, "1");

		//check the end bit
		int n = rs[0].length();
		int a = rs[0].charAt(n-1) - '0';
		int b = n > 1? rs[0].charAt(n-2) - '0' : 0;
		if (a + b + '0' != ms.charAt(ms.length()-1)) rs[0] = "NONE";

		n = rs[1].length();
		a = rs[1].charAt(n-1) - '0';
		b = n > 1? rs[1].charAt(n-2) - '0' : 0;
		if (a + b + '0' != ms.charAt(ms.length()-1)) rs[1] = "NONE";

		return rs;
	}

	String getCode(String ms, String dec) {
		int n = ms.length();
		if (equ(1, n))
			return dec;

		dec += String.valueOf(ms.charAt(0) - dec.charAt(0));

		//每次是计算i下标的下一个char,故此只需要循环到n-1就可以了
		for (int i = 1; i < n - 1; i++) {
			int a = dec.charAt(i - 1) - '0';
			int b = dec.charAt(i) - '0';
			int c = ms.charAt(i) - '0';
			int d = c - a - b;
			if (!equ(0, d) && !equ(1, d)) return "NONE";
			dec += String.valueOf(d);
		}		

		return dec;
	}

}
public class Main {
	public static void main(String[] args) {
		BinaryCode bc = new BinaryCode();
		String[] str = bc.decode("123210122");
		System.out.print(str[0] + '\n' + str[1]);
	}
}
时间: 2024-11-08 13:29:10

TopCoder SRMS 1 字符串处理问题 Java题解的相关文章

搜索文件或目录中包含字符串的文件 java小程序

package com.ruishenh.spring.test; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Enumeration; import java.

字符串转换成java.util.date类型和将java.util.date类型转换成java.sql.date类型

//将字符串转换成java.util.date类型 DateFormat format = new SimpleDateFormat("yyyyMMDD"); Date date1 = format.parse(startDate); //将java.util.date类型转换成java.sql.date类型 skg.statStartTime = new java.sql.Date(date1.getTime()); skg.statEndTime = new java.sql.Da

7 种将字符串反转的 Java 方法

import java.util.Stack;public class StringReverse { public static String reverse1(String s) { int length = s.length(); if (length <= 1) return s; String left = s.substring(0, length / 2); String right = s.substring(length / 2, length); return reverse

编程算法 - 字符串相同 代码(Java)

字符串相同 代码(Java) 本文地址: http://blog.csdn.net/caroline_wendy 题目: 实现一个算法, 确定一个字符串的所有字符是否全都不同. 假使不允许使用额外的数据结构, 又该如何处理. 解法1: 使用数据结构, 设置boolean数组, 把值(value)作为数组的索引(index), 判断数组是否重复. 解法2: 不使用数据结构, 可以通过位(bit)进行判断, 把每个字母映射2进制数的一位, 或运算("|")更新数字的位, 与运算("

LeetCode242_Valid Anagram(判断两个字符串是不是由完全一样字符组成) Java题解

题目: Given two strings s and t, write a function to determine if t is an anagram of s. For example, s = "anagram", t = "nagaram", return true. s = "rat", t = "car", return false. Note: You may assume the string conta

华为上机测试题(数字字符串转二进制-java)

PS:此题刚做完,满分,可参考 /*  * 题目:数字字符串转二进制 * 描述: 输入一串整数,将每个整数转换为二进制数,如果倒数第三个Bit是“0”,则输出“0”,如果是“1”,则输出“1”. 题目类别: 位运算 难度: 初级 分数: 60 运行时间限制: 10 Sec 内存限制: 128 MByte 阶段: 应聘考试 输入: 一串整数,长度小于1024,整数以空格隔开 输出: 1/0的整数串,空格隔开 样例输入: 240 0 样例输出: 0 0 答案提示: */ 1 import java.

LeetCode71 Simplify Path java题解

题目: Given an absolute path for a file (Unix-style), simplify it. For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c" 题解: 解题思路:这题是简化目录,每一级目录前面都有一个斜杠,我可以首先对斜杠进行分割,分割之后得到的结果无外乎4种情况:正常目录名称,空

【好好补题,因为没准题目还会再出第三遍!!】ACM字符串-组合数学(官方题解是数位DP来写)

ACM字符串 1.长度不能超过n 2.字符串中仅包含大写字母 3.生成的字符串必须包含字符串“ACM”,ACM字符串要求连在一块! ok,是不是很简单?现在告诉你n的值,你来告诉我这样的字符串有多少个 输入 输入一个正整数T,代表有T组数据 接下来T行,每行一个正整数n,n<=10. 输出 输出符合条件的字符串的数目 样例输入 1 3 样例输出 1 做题过程: 熬了三四个小时,WA了无数次!最终推出了组合数的公式! 首先暴力打表,嘿嘿!这样极大地压缩计算时间! 打表如下: 一:生成连续的7位绝对

leetcode424 替换后的最长重复字符 java题解

本题是比较典型的滑动窗口问题 这类问题一般通过一个滑动窗口就能在O(N)的时间复杂度下求解 本题可以先退化成考虑K=0的情况,此时题目就变成了求解字符串中最长连续子串长度问题了 我们先可以通过这个特例先了解一下滑动窗口的求解过程 上图的求解过程展示中,窗口从左至右不断扩张/滑动,当窗口触达字符串末尾字符时,运算结束,窗口的宽度为最终结果.初始窗口的宽度为1,我们不断的通过向当前窗口覆盖的子串后面追加一个字符看是否能满足我们的要求,如果满足窗口扩张,如果不满足,窗口向右滑动. 当K>0时,子串的条