Java with heavy use of regular expressions


  • 0
    J
    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    
    public class Solution {
    	public String solveEquation(String equation) {
    		String[] halves = equation.split("=");
    		int[] left = parseExpression(halves[0]);
    		int[] right = parseExpression(halves[1]);
    		if (left[0] == right[0]) {
    			if (left[1] == right[1]) {
    				return "Infinite solutions";
    			} else {
    				return "No solution";
    			}
    		} else {
    			return String.format("x=%d", (right[1] - left[1]) / (left[0] - right[0]));
    		}
    	}
    
    	private static int[] parseExpression(String expression) {
    		int[] values = new int[2]; // { coefficient of x, constant }
    		String[] pieces = expression.split("(?=-|\\+)");
    		Pattern pattern = Pattern.compile("^(-|\\+)?(\\d*)(x)?$");
    		for (String piece : pieces) {
    			Matcher m = pattern.matcher(piece);
    			m.find();
    			String sign = m.group(1);
    			String number = m.group(2);
    			String variable = m.group(3);
    			boolean negative = sign != null && sign.equals("-");
    			int coefficient = number.isEmpty() ? 1 : Integer.parseInt(number);
    			int index = variable == null ? 1 : 0;
    			values[index] += negative ? -coefficient : coefficient;
    		}
    		return values;
    	}
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.