JavaC++算法题解leetcode1592重新排列单词间的空格

Viridis ·
更新时间:2024-09-20
· 1977 次阅读

目录

题目要求

思路:模拟

Java

C++

Rust

题目要求

思路:模拟

模拟就完了

统计空格数量和单词数量,计算单词间应有的空格数,将它们依次放入结果字符串,若有余数则在末尾进行填补。

Java class Solution { public String reorderSpaces(String text) { int n = text.length(), spcnt = 0; List<String> words = new ArrayList<>(); for (int i = 0; i < n; ) { if (text.charAt(i) == ' ' && ++i >= 0 && ++spcnt >= 0) continue; int j = i; while (j < n && text.charAt(j) != ' ') j++; words.add(text.substring(i, j)); // 单词 i = j; } StringBuilder res = new StringBuilder(); int m = words.size(), dis = spcnt / Math.max(m - 1, 1); String spcs = ""; // 两单词间的空格 while (dis-- > 0) spcs += " "; for (int i = 0; i < m; i++) { res.append(words.get(i)); if (i != m - 1) res.append(spcs); } while (res.length() != n) res.append(" "); return res.toString(); } }

时间复杂度:O(n)

空间复杂度:O(n),结果的空间开销

C++ class Solution { public: string reorderSpaces(string text) { int n = text.size(), spcnt = 0; vector<string> words; for (int i = 0; i < n; ) { if (text[i] == ' ' && ++i >= 0 && ++spcnt >= 0) continue; int j = i; while (j < n && text[j] != ' ') j++; words.emplace_back(text.substr(i, j - i)); // 单词 i = j; } string res; int m = words.size(), dis = spcnt / max(m - 1, 1); string spcs = ""; // 两单词之间的空格 while (dis-- > 0) spcs += " "; for (int i = 0; i < m; i++) { res += words[i]; if (i != m - 1) res += spcs; } while (res.size() != n) res += " "; return res; } };

时间复杂度:O(n)

空间复杂度:O(n),结果的空间开销

Rust

rust有很方便的函数用以统计空格和单词,也有很方便的repeat构成单词之间需要的空格。

impl Solution { pub fn reorder_spaces(text: String) -> String { let spcnt = text.chars().filter(|&c| c == ' ').count(); let words: Vec<String> = text.split_whitespace().map(|s| s.to_string()).collect(); let mut res = String::new(); if words.len() == 1 { res.push_str(&words[0]); res.push_str(&" ".repeat(spcnt)); return res } for i in 0..words.len() { res.push_str(&words[i]); res.push_str(&" ".repeat( if i < words.len() - 1 { spcnt / (words.len() - 1) } else { spcnt - spcnt / (words.len() - 1) * (words.len() - 1) })); } res } }

时间复杂度:O(n)

空间复杂度:O(n),结果的空间开销

以上就是Java C++算法题解leetcode1592重新排列单词间的空格的详细内容,更多关于Java C++ 单词间空格重排的资料请关注软件开发网其它相关文章!



排列 javac leetcode 算法 单词

需要 登录 后方可回复, 如果你还没有账号请 注册新账号