@@ -76,45 +76,60 @@ private int sumArray(String json) {
76
76
}
77
77
78
78
private int sumObject (String json ) {
79
- // Check if object contains "red" as a value
80
- Pattern redPattern = Pattern .compile (":\\ s*\" red\" " );
81
- Matcher redMatcher = redPattern .matcher (json );
82
- if (redMatcher .find ()) {
83
- return 0 ;
84
- }
85
-
86
79
int sum = 0 ;
87
80
int depth = 0 ;
88
81
int start = 1 ;
89
82
boolean inString = false ;
83
+ boolean hasRed = false ;
84
+ StringBuilder currentValue = new StringBuilder ();
90
85
91
86
for (int i = 1 ; i < json .length () - 1 ; i ++) {
92
87
char c = json .charAt (i );
88
+
93
89
if (c == '"' ) {
90
+ if (!inString && depth == 0 ) {
91
+ currentValue .setLength (0 );
92
+ }
94
93
inString = !inString ;
94
+ continue ;
95
+ }
96
+
97
+ if (inString ) {
98
+ currentValue .append (c );
99
+ continue ;
95
100
}
96
- if (inString ) continue ;
97
101
98
102
if (c == '[' || c == '{' ) {
99
103
depth ++;
100
104
} else if (c == ']' || c == '}' ) {
101
105
depth --;
106
+ } else if (c == ':' && depth == 0 ) {
107
+ String value = currentValue .toString ();
108
+ currentValue .setLength (0 );
109
+ start = i + 1 ;
102
110
} else if (c == ',' && depth == 0 ) {
103
- String part = json .substring (start , i ).trim ();
104
- int colonIndex = part .indexOf (':' );
105
- if (colonIndex != -1 ) {
106
- sum += sumJson (part .substring (colonIndex + 1 ).trim ());
111
+ String value = json .substring (start , i ).trim ();
112
+ if (value .equals ("\" red\" " )) {
113
+ return 0 ;
114
+ }
115
+ if (!value .isEmpty ()) {
116
+ sum += sumJson (value );
107
117
}
108
118
start = i + 1 ;
109
119
}
110
120
}
121
+
122
+ // Process the last value
111
123
if (start < json .length () - 1 ) {
112
- String part = json .substring (start , json .length () - 1 ).trim ();
113
- int colonIndex = part .indexOf (':' );
114
- if (colonIndex != -1 ) {
115
- sum += sumJson (part .substring (colonIndex + 1 ).trim ());
124
+ String value = json .substring (start , json .length () - 1 ).trim ();
125
+ if (value .equals ("\" red\" " )) {
126
+ return 0 ;
127
+ }
128
+ if (!value .isEmpty ()) {
129
+ sum += sumJson (value );
116
130
}
117
131
}
132
+
118
133
return sum ;
119
134
}
120
135
}
0 commit comments