@@ -215,8 +215,57 @@ public String reorganizeString_1(String S) {
215215 }
216216
217217 // V2
218+ // IDEA : HASHMAP + array + 26 alphabet consideration (gpt)
219+ public String reorganizeString_2 (String S ) {
220+ // Step 1: Count the frequency of each character using an array
221+ int [] charCounts = new int [26 ];
222+ for (char c : S .toCharArray ()) {
223+ charCounts [c - 'a' ]++;
224+ }
225+
226+ // Step 2: Find the most frequent character
227+ int maxCount = 0 , maxCharIndex = -1 ;
228+ for (int i = 0 ; i < 26 ; i ++) {
229+ if (charCounts [i ] > maxCount ) {
230+ maxCount = charCounts [i ];
231+ maxCharIndex = i ;
232+ }
233+ }
234+
235+ // Step 3: If the most frequent character is more than half the string length, return ""
236+ if (maxCount > (S .length () + 1 ) / 2 ) {
237+ return "" ;
238+ }
239+
240+ // Step 4: Arrange characters
241+ char [] result = new char [S .length ()];
242+ int index = 0 ;
243+
244+ // Fill the most frequent character first
245+ while (charCounts [maxCharIndex ] > 0 ) {
246+ result [index ] = (char ) (maxCharIndex + 'a' );
247+ index += 2 ; // Fill at even indices first
248+ charCounts [maxCharIndex ]--;
249+ }
250+
251+ // Fill the remaining characters
252+ for (int i = 0 ; i < 26 ; i ++) {
253+ while (charCounts [i ] > 0 ) {
254+ if (index >= S .length ()) {
255+ index = 1 ; // Switch to odd indices
256+ }
257+ result [index ] = (char ) (i + 'a' );
258+ index += 2 ;
259+ charCounts [i ]--;
260+ }
261+ }
262+
263+ return new String (result );
264+ }
265+
266+ // V3
218267 // https://leetcode.com/problems/reorganize-string/solutions/3948228/100-fast-priorityqueue-with-explanation-c-java-python-c/
219- public String reorganizeString_2 (String s ) {
268+ public String reorganizeString_3 (String s ) {
220269 int [] f = new int [26 ];
221270 int n = s .length ();
222271
@@ -266,9 +315,9 @@ class Pair {
266315 }
267316
268317
269- // V3
318+ // V4
270319 // https://leetcode.com/problems/reorganize-string/solutions/3948110/easy-solution-python3-c-c-java-python-with-image/
271- public String reorganizeString_3 (String s ) {
320+ public String reorganizeString_4 (String s ) {
272321 Map <Character , Integer > count = new HashMap <>();
273322 for (char c : s .toCharArray ()) {
274323 count .put (c , count .getOrDefault (c , 0 ) + 1 );
@@ -355,5 +404,5 @@ private void heapifyUp(List<int[]> heap, int index) {
355404 }
356405 }
357406
358- // V3
407+ // V5
359408}
0 commit comments