Java C++算法題解leetcode1592重新排列單詞間的空格
更新時間:2022年09月14日 10:28:13 作者:AnjaVon
這篇文章主要為大家介紹了Java C++算法題解leetcode1592重新排列單詞間的空格示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
題目要求
思路:模擬
- 模擬就完了
- 統(tǒng)計空格數(shù)量和單詞數(shù)量,計算單詞間應有的空格數(shù),將它們依次放入結果字符串,若有余數(shù)則在末尾進行填補。
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有很方便的函數(shù)用以統(tǒng)計空格和單詞,也有很方便的
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++ 單詞間空格重排的資料請關注腳本之家其它相關文章!
相關文章
C++中strlen函數(shù)的三種實現(xiàn)方法
在C語言中我們要獲取字符串的長度,可以使用strlen?函數(shù),strlen?函數(shù)計算字符串的長度時,直到空結束字符,但不包括空結束字符,因為strlen函數(shù)時不包含最后的結束字符的,因此一般使用strlen函數(shù)計算的字符串的長度會比使用sizeof計算的字符串的字節(jié)數(shù)要小2022-05-05OpenCV中的cv::Mat函數(shù)將數(shù)據(jù)寫入txt文件
這篇文章主要介紹了OpenCVcv::Mat中的數(shù)據(jù)按行列寫入txt文件中,需要的朋友可以參考下2018-05-05