524. 左填充
实现一个leftpad库,如果不知道什么是leftpad可以看样例
样例
例1:
输入:
leftpad("foo", 5)
输出:
" foo"
例2:
输入:
leftpad("foobar", 6)
输出:
"foobar"
例3:
输入:
leftpad("1", 2, "0")
输出:
"01"
挑战
使用尽量少的内存
输入测试数据
(
每行一个参数
)
如何理解测试数据?
public class StringUtils {
static public String leftPad(String originalStr, int size) {
// Write your code here
int length=originalStr.length();
if(originalStr.length()<size){
StringBuilder ret= new StringBuilder();
for (int i = length; i < size; i++) {
ret.append(" ");
}
ret.append(originalStr);
return ret.toString();
}else{
return originalStr;
}
}
/*
* @param originalStr: the string we want to append to
* @param size: the target length of the string
* @param padChar: the character to pad to the left side of the string
* @return: A string
*/
static public String leftPad(String originalStr, int size, char padChar) {
// write your code here
int length=originalStr.length();
if(originalStr.length()<size){
StringBuilder ret= new StringBuilder();
for (int i = length; i < size; i++) {
ret.append(padChar);
}
ret.append(originalStr);
return ret.toString();
}else{
return originalStr;
}
}
}