Имя пользователя:
Пароль:  
Помощь | Регистрация | Забыли пароль?  

Показать сообщение отдельно

Аватара для ferget

Разный


Сообщения: 1294
Благодарности: 359

Профиль | Отправить PM | Цитировать


не совсем понятно, что значит не много
ну например так

Код: Выделить весь код
import java.util.*;

public class Answer1 {

	private String name;
	private Answer1 firstChild;
	private Answer1 nextSibling;

	Answer1(String n, Answer1 d, Answer1 r) {
		name = n;
		firstChild = d;
		nextSibling = r;
	}

	public static Answer1 parseTree(String s) {
		if (s == null || s.isEmpty()) {
			return null;
		}

		StringTokenizer mingi = new StringTokenizer(s, ",()", true);
		String midagi = mingi.nextToken();
		String Q = "", E = "", V = "";

		while (mingi.hasMoreTokens()) {
			Q = mingi.nextToken();
			if (Q.equals("(")) {
				Q = mingi.nextToken();
				int closed = 0;
				while (closed < 1) {
					E = E + Q;
					Q = mingi.nextToken();
					closed = findBrackets(Q, closed);
				}
			}
			if (Q.equals(",")) {
				while (mingi.hasMoreTokens()) {
					V = V + mingi.nextToken();
				}
			}
		}
		return new Answer1(midagi, Answer1.parseTree(E), Answer1.parseTree(V));
	}

	private static int findBrackets(String str, int num) {
		if (str.equals("(")) {
			return num - 1;
		} else if (str.equals(")")) {
			return num + 1;
		}
		return num;
	}

	public String rightParentheticRepresentation() {
		String Returned = "";
		if (firstChild != null) {
			Returned += "(" + firstChild.rightParentheticRepresentation() + ")";
		}
		Returned += name;
		if (nextSibling != null) {
			Returned += "," + nextSibling.rightParentheticRepresentation();
		}
		return Returned;
	}

	public static void main(String[] param) {
		String s = "A(B,C)";
		Answer1 t = Answer1.parseTree(s);
		String v = t.rightParentheticRepresentation();
		System.out.println(s + " ==> " + v); // A(B,C) ==> (B,C)A
		s = "A(C,B)";
		String Dam = "";
		Dam = s + " ==> "
				+ (Answer1.parseTree(s).rightParentheticRepresentation());
		int passedOf3 = 0;
		if (Dam.equals(s + " ==> " + "(C,B)A")) {
			passedOf3++;
			System.out.println("Test 1 OK!");
		}
		s = "B(D(C,H),B(W,M))";
		Dam = s + " ==> "
				+ (Answer1.parseTree(s).rightParentheticRepresentation());
		if (Dam.equals(s + " ==> " + "((C,H)D,(W,M)B)B")) {
			passedOf3++;
			System.out.println("Test 2 OK!");
		}
		s = "C(I(K,E(A,F)),Y(B,O))";
		Dam = s + " ==> "
				+ (Answer1.parseTree(s).rightParentheticRepresentation());
		if (Dam.equals(s + " ==> " + "((K,(A,F)E)I,(B,O)Y)C")) {
			passedOf3++;
			System.out.println("Test 3 OK!");
		}
		if (passedOf3 == 3) {
			System.out.println("All tests passed!");
		} else
			System.out.println("Error, some tests failed.");
	}
}

Отправлено: 20:45, 10-11-2012 | #6