日期:2014-05-20 浏览次数:20702 次
import java.util.*; public class csdn { public static void main(String[] args) throws Throwable { String testData[] = {"&((name=wang))(age=20)", "&((name=wang)(age=20)", "&(name=wang))(age=20)", "&(name=wang)))((age=20)", "&(((name=wang))((age=20))))"}; for (String str : testData) { //测试数据 convert(str); } } public static String convert(String str) { Stack<String> st = new Stack<String>(); List<String> ls = new ArrayList<String>(); StringBuilder sb = new StringBuilder(); boolean match = false; for (int i=0; i<str.length(); i++) { //先转换多余的")" String s = str.substring(i, i+1); if (s.equals(")")) { sb.delete(0, sb.length()); match = false; while (st.size() > 0) { String ss = st.pop(); if (ss.equals("(")) { if (sb.length() == 0 || (sb.charAt(0) == '(' && sb.charAt(sb.length()-1) == ')')) { st.push(sb.toString()); } else { sb.insert(0, ss); sb.append(s); st.push(sb.toString()); } match = true; break; } else { sb.insert(0, ss); } } if (!match) { if (sb.charAt(sb.length()-1) == ')') { sb.deleteCharAt(sb.length()-1); sb.append(String.format("\\%x", (int)(')'))); sb.append(s); } else { sb.append(String.format("\\%x", (int)(')'))); } st.push(sb.toString()); } } else { st.push(s); } } while (st.size() > 0) { //再转换多余的"(" String s = st.pop(); if (s.equals("(")) { if (ls.size() > 0) { String ss = ls.remove(0); if (ss.startsWith("(") && ss.endsWith(")")) { ls.add(0, String.format("%s\\%x%s", s, (int)('('), ss.substring(1))); } else { ls.add(0, String.format("\\%x", (int)('('))); } } else { ls.add(String.format("\\%x", (int)('('))); } } else { ls.add(0, s); } } sb.delete(0, sb.length()); for (String s : ls) { //获得最后结果 sb.append(s); } System.out.println(sb); return sb.toString(); } }