You are given a string
Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as
Return the string after rearranging the spaces.
text
of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word.Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as
text
.Return the string after rearranging the spaces.
Example 1:
Input: text = " this is a sentence "
Output: "this is a sentence"
Approach
Java
import java.util.List;import java.util.Stack;public class RearrangeSpacesBetweenWords {public static void main(String[] args) {String text = " this is a sentence ";System.out.println(reorderSpaces(text));}static String reorderSpaces(String text) {int cnt = 0;int i = 0;List<String> v = new Stack<String>();int n = text.length();while (i < n) {String str = "";while (i < n && text.charAt(i) == ' ') {cnt++;i++;}while (i < n && text.charAt(i) != ' ') {str += text.charAt(i);i++;}if (str.length() > 0)v.add(str);}String res = "";int x = v.size();if (x == 1) {res += v.get(0);while (cnt > 0) {cnt--;res += ' ';}return res;}int y = cnt / (x - 1);int p = cnt % (x - 1);for (int j = 0; j < v.size() - 1; j++) {res += v.get(j);for (int k = 0; k < y; k++)res += ' ';}res += v.get(v.size() - 1);while (p > 0) {p--;res += ' ';}return res;}}
C++
#include <bits/stdc++.h>using namespace std;string reorderSpaces(string text){int cnt = 0;int i = 0;vector<string> v;int n = text.size();while (i < n){string str = "";while (i < n && text[i] == ' '){cnt++;i++;}while (i < n && text[i] != ' '){str += text[i];i++;}if (str.size() > 0)v.push_back(str);}string res = "";int x = v.size();if (x == 1){res += v[0];while (cnt--)res += ' ';return res;}int y = cnt / (x - 1);int p = cnt % (x - 1);for (int i = 0; i < v.size() - 1; i++){res += v[i];for (int j = 0; j < y; j++)res += ' ';}res += v[v.size() - 1];while (p--)res += ' ';return res;}int main(){string text = " this is a sentence ";cout << reorderSpaces(text);return 0;}
No comments:
Post a Comment