Rearrange a string so that all same characters become d distance away

http://www.geeksforgeeks.org/rearrange-a-string-so-that-all-same-characters-become-at-least-d-distance-away/

Given a string and a positive integer d. Some characters may be repeated in the given string. Rearrange characters of the given string such that the same characters become d distance away from each other. Note that there can be many possible rearrangements, the output should be one of the possible rearrangements. If no such arrangement is possible, that should also be reported.
Expected time complexity is O(n) where n is length of input string.

Examples:
Input:  "abb", d = 2
Output: "bab"

Input:  "aacbbc", d = 3
Output: "abcabc"

Input: "geeksforgeeks", d = 3
Output: egkegkesfesor

Input:  "aaa",  d = 2
Output: Cannot be rearranged
 1 public class Solution{
 2
 3     public static int MAX = 26;
 4     static class CharFreq {
 5         char c;
 6         int f;
 7         public CharFreq(char c, int f) {
 8             this.c = c;
 9             this.f = f;
10         }
11     }
12
13     public static void main(String []args){
14         String str = rearrange("geeksforgeeks",3);
15         if (str != null)
16             System.out.println(str);
17     }
18
19     public static String rearrange(String str, int k) {
20         if (str.length() <= 1) return str;
21
22         CharFreq[] cf = new CharFreq[MAX];
23         int count = 0; // number of different characters
24
25         for (int i=0; i<MAX; i++) {
26             cf[i] = new CharFreq((char) (‘a‘+i), 0);
27         }
28
29         for (int i=0; i<str.length(); i++) {
30             char ch = str.charAt(i);
31             cf[ch-‘a‘].f++;
32             if (cf[ch-‘a‘].f == 1) count++;
33         }
34
35         buildHeap(cf, MAX);
36
37         char[] str1 = new char[str.length()];
38         boolean[] occu = new boolean[str.length()]; // judge if the seat is occupied
39         for (int i = 0; i<count; i++) {
40             CharFreq chfreq = extractMax(cf, MAX-i);
41             int pt = i;
42             while (occu[pt]) pt++; // find the first place that is not occupied
43
44             for (int j=0; j<chfreq.f; j++) {
45                 if (pt >= str1.length)
46                     return null;
47                 str1[pt] = chfreq.c;
48                 occu[pt] = true;
49                 pt += k;
50             }
51         }
52         return new String(str1);
53     }
54
55     private static void buildHeap(CharFreq[] cf, int size) {
56         int i = (size-1) / 2;
57         while (i>=0) {
58             maxHeapify(cf, i, size);
59             i--;
60         }
61     }
62
63     private static void swap(CharFreq cf1, CharFreq cf2) {
64         char c = cf1.c;
65         int f = cf1.f;
66         cf1.c = cf2.c;
67         cf1.f = cf2.f;
68         cf2.c = c;
69         cf2.f = f;
70     }
71
72     private static void maxHeapify(CharFreq[] cf, int node, int size) {
73         int l = node * 2 + 1;
74         int r = node * 2 + 2;
75         int largest = node;
76         if (l < size && cf[l].f > cf[node].f) {
77             largest = l;
78         }
79         if (r < size && cf[r].f > cf[largest].f) {
80             largest = r;
81         }
82         if (largest != node) {
83             swap(cf[node], cf[largest]);
84             maxHeapify(cf, largest, size);
85         }
86     }
87
88     private static CharFreq extractMax(CharFreq[] cf, int size) {
89         CharFreq max = cf[0];
90         cf[0] = cf[size-1];
91         cf[size-1] = null;
92         maxHeapify(cf, 0, size-1);
93         return max;
94     }
95 }

Analysis:

Time Complexity: Time complexity of above implementation is O(n + mLog(MAX)). Here n is the length of str, m is count of distinct characters in str[] and MAX is maximum possible different characters. MAX is typically 256 (a constant) and m is smaller than MAX. So the time complexity can be considered as O(n).

More Analysis:
The above code can be optimized to store only m characters in heap, we have kept it this way to keep the code simple. So the time complexity can be improved to O(n + mLogm). It doesn’t much matter through as MAX is a constant.

Also, the above algorithm can be implemented using a O(mLogm) sorting algorithm. The first steps of above algorithm remain same. Instead of building a heap, we can sort the freq[] array in non-increasing order of frequencies and then consider all characters one by one from sorted array.

时间: 2024-11-03 10:09:35

Rearrange a string so that all same characters become d distance away的相关文章

[string]Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest subst

[LeetCode] Rearrange String k Distance Apart 按距离为k隔离重排字符串

Given a non-empty string str and an integer k, rearrange the string such that the same characters are at least distance k from each other. All input strings are given in lowercase letters. If it is not possible to rearrange the string, return an empt

Day9 string.characters.count and closures

//                                      **Day9 //                                      CloseSure var arr:[Int] = [1,2,3,4,5,9,8,7,6,0] arr.sort() func compareTwoInts(a:Int,b:Int) -> Bool { return a>b } arr.sort(compareTwoInts) // summary    sorted b

Java源代码学习 -- java.lang.String

java.lang.String是使用频率非常高的类.要想更好的使用java.lang.String类,了解其源代码实现是非常有必要的.由java.lang.String,自然联想到java.lang.StringBuffer和java.lang.StringBuilder,下篇文章再来研究java.lang.StringBuffer和java.lang.StringBuilder. 重要属性 java.lang.String对象中字符串主要是以字符数组的形式存储.当调用对象方法获取字符串长度时

1050. String Subtraction (20)【字符串处理】——PAT (Advanced Level) Practise

题目信息 1050. String Subtraction (20) 时间限制10 ms 内存限制65536 kB 代码长度限制16000 B Given two strings S1 and S2, S = S1 - S2 is defined to be the remaining string after taking all the characters in S2 from S1. Your task is simply to calculate S1 - S2 for any giv

String源码

/* * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package java.lang; import java.io.ObjectStreamClass;import java.io.ObjectStreamField;import java.

python的string.strip(s[, chars])方法的各种小细节

下面的英文说明是官方给出: string.strip(s[, chars]) Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the stri

UVA 10739 String to Palindrome(DP)

In this problem you are asked to convert a string into a palindrome with minimum number of operations. The operations are described below: Here you'd have the ultimate freedom. You are allowed to: Add any character at any position Remove any characte

python中string.casefold和string.lower区别

string.casefold和string.lower 区别 python 3.3 引入了string.casefold 方法,其效果和 string.lower 非常类似,都可以把字符串变成小写,那么它们之间有什么区别?他们各自的应用场景? 对 Unicode 的时候用 casefold string.casefold官方说明: Casefolding is similar to lowercasing but more aggressive because it is intended t