LintCode之左填充

题目描述:

 

分析:由样例可知,第二个参数表示要返回的字符串的最小长度,所以当给定字符串的长度小于规定字符串最小长度时就在左边填充空格,另外还有一个重载方法leftpad的第三个参数指定左边填充的字符。需要注意的是:只有但字符串长度小于规定的字符串最小长度时才需要左填充,否则,直接返回原字符串。

我的代码:

 1 public class StringUtils {
 2     /**
 3      * @param originalStr: the string we want to append to with spaces
 4      * @param size: the target length of the string
 5      * @return: A string
 6      */
 7     static public String leftPad(String originalStr, int size) {
 8         int n;
 9         if(originalStr == null) {
10             n =0;
11         }else {
12             n = originalStr.length();
13         }
14         //当字符串长度大于等于size时,直接返回原字符串
15         if(n >= size) {
16             return originalStr;
17         }else {
18             n = size - n;
19             for(int i=0; i<n; i++) {
20                 originalStr = " "+originalStr;
21             }
22             return originalStr;
23         }
24     }
25 
26     /*
27      * @param originalStr: the string we want to append to
28      * @param size: the target length of the string
29      * @param padChar: the character to pad to the left side of the string
30      * @return: A string
31      */
32     static public String leftPad(String originalStr, int size, char padChar) {
33          int n;
34         if(originalStr == null) {
35             n =0;
36         }else {
37             n = originalStr.length();
38         }
39         if(n >= size) {
40             return originalStr;
41         }else {
42             n = size - n;
43             for(int i=0; i<n; i++) {
44                 originalStr = padChar+originalStr;
45             }
46             return originalStr;
47         }
48     }
49 }

 

posted @ 2017-11-08 20:02  zwt3  阅读(344)  评论(0编辑  收藏  举报