例一:
- /*通信编码
- 假设通信的物理设备只能表示1和0两种状态。
- 1和0状态都不能持续太久,否则物理设备会出现故障。因而人们设计出一种变通的方法:
- 多个0后人为地补入一个1
- 多个1后人为地补入一个0
- 当然,在解码的时候,要相应处理。
- 下面我们用串来模拟这个算法。
- 假设有需要通信的串:
- String s = "1010100100100001011110100010101010100001010101111";
- 连续的3个0,后需要插入一个1
- 连续的3个1,后需要输入一个0
- 1010100100100001011110100010101010100001010101111
- 10101001001000101011101010001101010....
- 想一想,加码处理后,需要把它再解码出来。*/
- public class C7 {
- public static String encrypt (String s) {
- String s2 = s.replaceAll("(0{3})", "$11");
- s2 = s2.replaceAll("(1{3})", "$10");
- return s2;
- }
- public static String decrypt(String s) {
- String s2 = s.replaceAll("(1{3})0", "$1");
- s2 = s2.replaceAll("(0{3})1", "$1");
- return s2;
- }
- public static void main(String[] args) {
- String s = "1010100100100001011110100010101010100001010101111";
- System.out.println(s);
- String s1 = encrypt(s);
- System.out.println(s1);
- String s2 = decrypt(s1);
- System.out.println(s2);
- //System.out.println(s.equalsIgnoreCase(s2));
- }
- }
例二:
- /*格式检查
- xml 文件主要是由标签构成的。
- 类似:
- .....
- .dfsfs
- kkkk
- 请编写一个程序,能够发现其中匹配不完整的标签。
- 例如:
- sdfsfs
- 此时, 标签的匹配就是不完整的。*/
- import java.io.*;
- import java.util.*;
- import java.util.regex.*;
- public class C8
- {
- public static void main(String[] args) throws Exception
- {
- BufferedReader br = new BufferedReader(new InputStreamReader(
- new FileInputStream("a.txt")));
- String x = "";
- for(;;){
- String s = br.readLine();
- if(s==null) break;
- x += s;
- }
- x = x.replaceAll("\\<[^\\<\\>]+\\/>",""); //删除封闭标签
- //匹配某个起始标签或结束标签
- Pattern pt = Pattern.compile(
- "\\<([a-zA-Z0-9]+)( +[^\\<\\>]*)?\\>|\\</([a-zA-Z0-9]+)\\>");
- Stack<String> stk = new Stack<String>();
- boolean tag = true; // 假设匹配
- Matcher m = pt.matcher(x);
- while(m.find()){
- if(m.group(1) != null) stk.push(m.group(1));
- if(m.group(3) != null){
- if(stk.isEmpty()){
- tag = false;
- break;
- }
- if(stk.pop().equals(m.group(3))==false){
- tag = false;
- break;
- }
- }
- }
- if(stk.isEmpty()==false) tag = false;
- System.out.println(tag);
- }
- }