把key value字符串轉爲tree

package kvtoString;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
//k1=v1,k2=(k3=v3,k4=(k6=v6),k7=v7),k5=v5
//
class Node{
	String key;
	String value;
	ArrayList<Node> set=new ArrayList<>();
	public Node(String key,String value){
		this.key=key;
		this.value=value;
	}
	
	
}
public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str="k1=v1,k2=(k3=v3,k4=(k6=v6),k7=v7),k5=v5";
		String pre="";
		String key=null,value=null;
		Stack<Node> stack=new Stack<>();
		Node head=new Node(null, null);
		stack.add(head);
		for(int i=0;i<str.length();++i){
			char now=str.charAt(i);
		
			if(now=='='){
				if(str.charAt(i+1)=='('){		
					Node n=stack.peek();
					Node ne=new Node(key, null);
					n.set.add(ne);
					stack.push(ne);
					key=null;
				}				
			}
			else if(now==')'){
				if(str.charAt(i-1)!=')'){
					Node node=stack.pop();
					node.set.add(new Node(key, value));
					key=null;
					value=null;
				}
				else{
					stack.pop();
				}
			}
			else if(now=='('){
				
			}
			else if(now==','){
				if(str.charAt(i-1)!=')'){
					Node node=stack.peek();
					node.set.add(new Node(key, value));
					key=null;
					value=null;
				}
			}
			else if(value !=null){
				value=value+String.valueOf(now);
				if(i==str.length()-1){
					Node node=stack.peek();
					node.set.add(new Node(key, value));
					key=null;
					value=null;
				}
			}
			else if(key==null){
				key=String.valueOf(now);
			}
			else if(key!=null){
				if(str.charAt(i-1)=='='){
					value=String.valueOf(now);
					if(i==str.length()-1){
						Node node=stack.peek();
						node.set.add(new Node(key, value));
						key=null;
						value=null;
					}
				}
				else
					key=key+String.valueOf(now);
				
			}
			
			
		}
		System.out.println(head.toString());

	}

}

点赞