您的位置:首页 > 编程语言

【算法】程序猿不写代码是不对的71

2017-06-15 17:43 204 查看
package com.kingdz.algorithm.time201706;

/**
* <pre>
* 打印U型字符串
*
* http://judgecode.com/problems/1003 *
* Given a string of length n, please print it into shape of U.
* The characters must be printed in the original order,
* starting top-down from the left vertical line with n1 characters,
* then left to right along the bottom line with n2 characters,
* and finally bottom-up along the vertical line with n3 characters.
* And more, we would like U to be as squared as possible -- that is,
* it must satisfy that n1 = n3 = max { k| k <= n2 for all 3 <= n2 <= N } with n1 + n2 + n3 - 2 = n.
* For example the word “helloworld” should be:
*
* h  d
* e  l
* l  r
* lowo
* </pre>
*
* @author kingdz
*
*/
public class Algo15 {

public static void main(String[] args) {
String input = "helloworldnihaoma";
int length = input.length();
int n1 = length / 3;
int n3 = length - n1 - n1 - 2;

StringBuilder strb = new StringBuilder();
char[] strArray = input.toCharArray();
for (int i = 0; i < n1 + 1; i++) {
if (i == n1) {
// 特殊处理最后一行
strb.append(input.substring(i, length - i));
break;
}

char left = strArray[i];
char righ = strArray[length - i - 1];
strb.append(left);
for (int j = 0; j < n3; j++) {
strb.append(" ");
}
strb.append(righ);
strb.append("\n");
}
System.out.println(strb.toString());
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: