leetcode: Text Justification
2014-06-17 22:15
281 查看
最烦这种题,就是硬做,各种边界条件
class Solution { public: vector<string> fullJustify(vector<string> &words, int L) { vector< string> res; int cur_length = 0; string cur = ""; for( int i = 0; i < words.size(); ++i){ cur_length += words[i].size(); if( cur_length > L){ justify( cur, L); res.push_back(cur); cur = ""; cur_length = 0; --i; } else if( cur_length == L){ cur += words[i]; res.push_back( cur); cur = ""; cur_length = 0; } else{ cur = cur + words[i] + ' '; cur_length += 1; if( i + 1 == words.size()){ while( cur.size() < L) cur += ' '; res.push_back(cur); } } } return res; } void justify( string &s, int L){ s = s.substr( 0, s.size()-1); int sp_num = L - s.size(); string tmp; int cnt = 0; stringstream stream(s); while( stream >> tmp){ ++cnt; } if( cnt == 1 || cnt == 0){ string space( sp_num, ' '); s += space; return; } int sp_cnt = sp_num / ( cnt - 1); int lsp_cnt = sp_num - ( cnt - 1) * sp_cnt; string space( sp_cnt+1, ' '); string ss; stringstream stream2(s); while( stream2 >> tmp){ ss += tmp; if( lsp_cnt){ ss = ss + space + ' '; --lsp_cnt; } else ss += space; } s = ss.substr( 0, ss.length() - sp_cnt - 1); } };
相关文章推荐
- [LeetCode] Interleaving String
- LeetCode-Unique Binary Search Trees II
- Linked List Cycle II -- LeetCode
- [LeetCode] Search a 2D Matrix [25]
- LeetCode | Construct Binary Tree from Preorder and Inorder Traversal
- [C++]LeetCode: 7 Pascal's Triangle
- [LeetCode]155 Min Stack
- 【LeetCode】Recover BinarySearch Tree
- LeetCode: Valid Palindrome [125]
- [leetcode 189] Rotate Array
- [LeetCode]Search a 2D Matrix ||
- LeetCode 008 String to Integer (atoi)
- [LeetCode169]Majority Element求一个数组中出现次数大于n/2的数
- 《leetCode》: Maximum Depth of Binary Tree
- LeetCode *** 189. Rotate Array
- leetcode 144. Binary Tree Preorder Traversal
- 【Leetcode 动态规划】 不知如何分类 就都放这里了
- leetcode 【238 Product of Array Except Self】【Python】
- [LeetCode] 134. Gas Station
- LeetCode 419. Battleships in a Board