LeetCode OJ——Text Justification

http://oj.leetcode.com/problems/text-justification/

编译代码要看warnings!它提供了可能出问题的情况,比如类型转换上unsigned int < int的比较,要用计算机的思维。这道题终究还是没有AC,差不多就这样吧。

要养成好的代码习惯,可以一边写代码,一边debug。注意变量命名之类的,常规问题。

Good good study!

 #include <iostream>
#include <vector>
#include <string>
using namespace std; class Solution {
public:
vector< string> fullJustify(vector <string> & words, int L) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int alreadylen = ;
int beginindex = ,endindex = ;
int averagespace = ,firstspace = ;
vector<string > result; string onepiece("");
for(unsigned int index = ;index<words.size();index++)
{
beginindex = endindex = index;
alreadylen = ; while((index<words.size())&&( static_cast<int>(words[index].size()) <= (L-alreadylen)))
{
int wordsindexsize = words[index].size();
alreadylen += words[index].size()+;
index++;
} endindex = index; if(beginindex == endindex-)
{
onepiece.clear();
onepiece = words[beginindex];
if(L -words[beginindex].size()>)
onepiece.append( L-words[beginindex].size(),' ');
}
else if(index != words.size()+ && index!=words.size())
{
onepiece.clear();
averagespace = (L-alreadylen+)/(endindex-beginindex-);
firstspace = averagespace + (L -alreadylen+)%(endindex-beginindex-); for(int tt = beginindex;tt<endindex;tt++)
{
onepiece +=words[tt];
if(tt==beginindex)
onepiece.append(firstspace+,' ' );
else if(tt!= endindex -)
onepiece.append(averagespace+,' ' );
}
}
else
{
onepiece.clear();
int alreadylength = ;
for(int tt = beginindex;tt<endindex;tt++)
{ onepiece += words[tt];
alreadylength += words[tt].size();
if(tt!=words.size()-)
{
onepiece.append(,' ' );
alreadylength++;
}
else
onepiece.append(L-alreadylength,' ' ); } }
index--;
result.push_back(onepiece);
}
return result;
}
}; int main()
{
Solution *mySolution = new Solution(); //words: [This, "is", "an", "example", "of", "text", "justification."]
//L: 16.
vector<string > words; /*words.push_back( "this");
words.push_back( "is");
words.push_back( "an");
words.push_back( "example");
words.push_back( "of");
words.push_back( "text");
words.push_back( "justification."); */
words.push_back( "what");
words.push_back( "must");
words.push_back( "be");
words.push_back( "shall");
words.push_back( "be.");
vector<string > output;
output = mySolution->fullJustify(words,);
for(unsigned int i = ;i<output.size();i++)
cout<<output[i]<<endl; return ;
}
上一篇:Alpha冲刺! Day6 - 砍柴


下一篇:【BZOJ-2597】剪刀石头布 最小费用最大流