diff options
author | Jack Sangdahl <[email protected]> | 2025-03-10 00:36:13 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-03-10 00:36:13 -0600 |
commit | 7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch) | |
tree | eb7a24ee2067f92245c57bb118e85a1baf15df50 /other/reorganise_string.cpp | |
parent | 5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff) | |
download | leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip |
chore: move cpp and rust code to directory
Diffstat (limited to 'other/reorganise_string.cpp')
-rw-r--r-- | other/reorganise_string.cpp | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/other/reorganise_string.cpp b/other/reorganise_string.cpp new file mode 100644 index 0000000..7a42643 --- /dev/null +++ b/other/reorganise_string.cpp @@ -0,0 +1,41 @@ +// 767. Reorganize String +#include "leetcode.h" + +/* + * given a string 's', rearrange the characters of 's' so that any two adjacent + * characters are not the same. return any possible arrangement of 's', or + * return "" if not possible. + */ + +class Solution { +public: + string reorganizeString(string s) { + vector<int> cnt(26); + int most_freq = 0, i = 0; + for (char c : s) + if (++cnt[c - 'a'] > cnt[most_freq]) + most_freq = (c - 'a'); + if (2 * cnt[most_freq] - 1 > s.size()) + return ""; + while (cnt[most_freq]) { + s[i] = ('a' + most_freq); + i += 2; + cnt[most_freq]--; + } + for (int j = 0; j < 26; j++) + while (cnt[j]) { + if (i >= s.size()) + i = 1; + s[i] = ('a' + j); + cnt[j]--; + i += 2; + } + return s; + } +}; + +int main() { + Solution obj; + cout << obj.reorganizeString("aab"); // expect: aba + cout << obj.reorganizeString("aaab"); // expect: +} |