【Text Justification】cpp

题目:

Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ‘ ‘ when necessary so that each line has exactly L characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

For the last line of text, it should be left justified and no extra space is inserted between words.

For example,
words: ["This", "is", "an", "example", "of", "text", "justification."]
L: 16.

Return the formatted lines as:

[
   "This    is    an",
   "example  of text",
   "justification.  "
]

Note: Each word is guaranteed not to exceed L in length.

click to show corner cases.

Corner Cases:

  • A line other than the last line might contain only one word. What should you do in this case?
    In this case, that line should be left-justified.

代码:

class Solution {
public:
    vector<string> fullJustify(vector<string>& words, int maxWidth) {
            vector<string> ret;
            vector<string> tmp; // words in one line
            int width = 0; // total width in one line
            const char BLANK=‘ ‘;
            int i=0;
            while ( i<words.size() )
            {
                // judge if a word can be added in a line
                if ( width+words[i].size() <= maxWidth )
                {
                    if ( width+words[i].size()==maxWidth )
                    {
                        tmp.push_back(words[i]);
                        width = maxWidth;
                    }
                    else
                    {
                        tmp.push_back(words[i]+string(1,BLANK));
                        width += words[i].size()+1;
                    }
                }
                // or create a new line & handle the words[i]
                else
                {
                    // CREAT A NEW LINE
                    // number of blank need to add
                    int blank_num =  maxWidth - width;
                    if ( tmp.back()[tmp.back().size()-1]==BLANK )
                    {
                        tmp.back() = string(tmp.back().begin(),tmp.back().end()-1);
                        blank_num = blank_num + 1;
                    }
                    // number of position for blanks
                    int pos_num = tmp.size()-1;
                    if ( pos_num==0 )
                    {
                        ret.push_back(tmp.back()+string(blank_num, BLANK));
                    }
                    else
                    {
                        // number of blanks remain to be evenly distributed
                        int blank_remain = blank_num % pos_num;
                        for ( int j=0; j<tmp.size()-1; ++j )
                        {
                            tmp[j] = tmp[j]+ string(blank_num/pos_num, BLANK);
                        }
                        for ( int j=0; j<blank_remain; ++j )
                        {
                            tmp[j] = tmp[j] + string(1, BLANK);
                        }
                        string str = "";
                        for ( int j=0; j<tmp.size(); ++j ) str += tmp[j];
                        ret.push_back(str);
                    }
                    // HANDLE THE words[i]
                    tmp.clear();
                    if ( words[i].size()==maxWidth )
                    {
                        tmp.push_back(words[i]);
                        width = maxWidth;
                    }
                    else
                    {
                        tmp.push_back(words[i]+string(1, BLANK));
                        width = words[i].size()+1;
                    }
                }
                ++i;
            }
            // address the remain line
            if ( tmp.size()!=0 )
            {
                int blank_num =  maxWidth - width;
                string last_line = "";
                for ( int i=0; i<tmp.size(); ++i ) last_line += tmp[i];
                ret.push_back(last_line+string(blank_num, BLANK));
            }
            return ret;
    }
};

tips:

1. 要对string的各种操作都很熟悉

2. 要理解对题意,重点是到底啥是evenly:意思是不能evenly,就从左边到右一个个分配。

3. 扫一扫各种test case,多扫几遍可以AC了。

这道题自己扫了4次,终于AC了;经验就是,如果不能做到第一次把所有关键细节都考虑完全了,至少把一些细节(诸如blank_num,pos_num,blank_remain)单独列拎出来,这样做的好处就是如果遇上各种需要考虑的corner cases可以单独处理这些关键细节,而不用影响其他的部分。

时间: 2024-11-10 22:00:27

【Text Justification】cpp的相关文章

【ZigZag Conversion】cpp

题目: The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAP

【Word Break】cpp

题目: Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, givens = "leetcode",dict = ["leet", "code"]. Return true becau

【Sudoku Solver】cpp

题目: Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character '.'. You may assume that there will be only one unique solution. A sudoku puzzle... ...and its solution numbers marked in red. 代码: cla

【Subsets II】cpp

题目: Given a collection of integers that might contain duplicates, nums, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example,If nums = [1,2,2], a sol

【LRU Cache】cpp

题目: Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.

【Rotate List】cpp

题目: Given a list, rotate the list to the right by k places, where k is non-negative. For example:Given 1->2->3->4->5->NULL and k = 2,return 4->5->1->2->3->NULL. 代码: /** * Definition for singly-linked list. * struct ListNode {

【Simplify Path】cpp

题目: Given an absolute path for a file (Unix-style), simplify it. For example,path = "/home/", => "/home"path = "/a/./b/../../c/", => "/c" click to show corner cases. Corner Cases: Did you consider the case whe

【Implement strStr() 】cpp

题目: Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Update (2014-11-02):The signature of the function had been updated to return the index instead of the pointer. If you st

【Valid Palindrome】cpp

题目: Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example,"A man, a plan, a canal: Panama" is a palindrome."race a car" is not a palindrome. Note:Have you consider tha