中级农民
- 积分
- 132
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-2-17
- 最后登录
- 1970-1-1
|
有个C#的代码,希望楼主可以参考下
- public IList<string> FullJustify(string[] words, int maxWidth) {
- var res = new List<string>();
-
- for(int i = 0, currIndex; i< words.Length; i = currIndex)
- //i: index of words
- //currIndex: the current index of words in the line
- //lineLen: Current total length of words in the line
- {
- int lineLen = -1; //we need to skip the space for last word hence start len is -1.
- for(currIndex = i; currIndex < words.Length && lineLen + words[currIndex].Length + 1 <= maxWidth; currIndex++ )
- lineLen = lineLen + words[currIndex].Length + 1; //default one space between words
-
- StringBuilder curStr = new StringBuilder(words[i]);
- int space = 1, extra = 0;
- //default value for evenlyDistributeSpaces-> deal with last line case
-
- //not 1 char, not last line
- //currIndex - i - 1 :
- //currIndex is already pointing to nex index
- // -1 mean n there are n-1 gap between n words
- if(currIndex != i+1 && currIndex != words.Length)
- {
- space = (maxWidth - lineLen) / (currIndex - i - 1) + 1; // +1 mean for the default one space between words
- extra = (maxWidth - lineLen) % (currIndex - i - 1);
- }
-
-
-
- //not 1 char, including last line
- for(int j = i + 1; j< currIndex; j++) //j: index of word in the current line
- {
- for(int s = space; s>0;s--) curStr.Append(" "); //Add the "even" space
- if(extra-- > 0) curStr.Append(" ");
- curStr.Append(words[j]);
- }
-
- //reach the last line
- int strLen = maxWidth - curStr.Length;
- while(strLen-- > 0) curStr.Append(" ");
- res.Add(curStr.ToString());
-
- }
-
- return res;
- }
复制代码 |
|