MCPcopy Index your code
hub / github.com/careercup/ctci / insertParensAround

Method insertParensAround

java/Chapter 9/Question9_11/Question.java:94–137  ·  view source on GitHub ↗
(String expression, int ind)

Source from the content-addressed store, hash-verified

92 }
93
94 public static String insertParensAround(String expression, int ind) {
95 int left = 0;
96 int right = 0;
97 int index = 0;
98 int count = 0;
99 for (int i = 0; i < expression.length(); i++) {
100 if (isOperator(expression.charAt(i))) {
101 if (count == ind) {
102 index = i;
103 }
104 count++;
105 }
106 }
107 count = 0;
108 for (int i = index - 1; i >= 0; i--) {
109 if (expression.charAt(i) == ')') {
110 count++;
111 } else if (expression.charAt(i) == '(') {
112 count--;
113 }
114 if (count == 0) {
115 left = i;
116 break;
117 }
118 }
119 count = 0;
120 for (int i = index + 1; i <= expression.length(); i++) {
121 if (expression.charAt(i) == '(') {
122 count++;
123 } else if (expression.charAt(i) == ')') {
124 count--;
125 }
126 if (count == 0) {
127 right = i;
128 break;
129 }
130 }
131 if (left == 0 && right == expression.length() - 1) {
132 return expression;
133 }
134 String newexpression = expression.substring(0, left) + '(' + expression.substring(left, right + 1) + ')' + expression.substring(right + 1);
135 return newexpression;
136
137 }
138
139 public static int bruteForce(String expression, HashMap<String, Boolean> completed, boolean result, boolean[] flags) {
140 int count = 0;

Callers 1

bruteForceMethod · 0.95

Calls 2

isOperatorMethod · 0.95
lengthMethod · 0.45

Tested by

no test coverage detected