资讯专栏INFORMATION COLUMN

[LintCode] Left Pad

X1nFLY / 2327人阅读

摘要:就是两个,一个有参数,一个没有,做法一样。用或放入前缀,直到新的字符串长度等于。

Problem

You know what, left pad is javascript package and referenced by React:
Github link

One day his author unpublished it, then a lot of javascript projects in the world broken.

You can see from github it"s only 11 lines.

You job is to implement the left pad function. If you do not know what left pad does, see examples below and guess.

Example
leftpad("foo", 5)
 "  foo"

leftpad("foobar", 6)
 "foobar"

leftpad("1", 2, "0")
 "01"
Note

就是两个method,一个有参数padChar,一个没有,做法一样。用" "padChar放入originalStr前缀,直到新的字符串长度等于size

Solution
public class StringUtils {
    static public String leftPad(String originalStr, int size) {
        int len = originalStr.length();
        StringBuilder sb = new StringBuilder();

        if (size <= len) return originalStr;
        else {
            for (int i = 0; i < size-len; i++) sb.append(" ");
            sb.append(originalStr);
        }
        return sb.toString();
    }
    static public String leftPad(String originalStr, int size, char padChar) {
        int len = originalStr.length();
        StringBuilder sb = new StringBuilder();

        if (size <= len) return originalStr;
        else {
            for (int i = 0; i < size-len; i++) sb.append(padChar);
            sb.append(originalStr);
        }
        return sb.toString();
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65804.html

相关文章

  • LintCode Coins in a line III

    摘要:复杂度思路参考的思路,对于,表示在从到的范围内,先手玩家能拿到的最大的硬币价值。对于状态,先手玩家有两种选择,要么拿的硬币,要么拿的硬币左边一个的或者右边一侧的,如果拿左侧的硬币,如果拿右侧的硬币,取两个值的最大值。 LintCode Coins in a line III There are n coins in a line. Two players take turns to ...

    focusj 评论0 收藏0
  • Lintcode Coins in a line II

    摘要:两个参赛者轮流从左边依次拿走或个硬币,直到没有硬币为止。计算两个人分别拿到的硬币总价值,价值高的人获胜。请判定第一个玩家是输还是赢样例给定数组返回给定数组返回复杂度思路考虑先手玩家在状态,表示在在第的硬币的时候,这一位玩家能拿到的最高价值。 LintCode Coins in a line II 有 n 个不同价值的硬币排成一条线。两个参赛者轮流从左边依次拿走 1 或 2 个硬币,直...

    2shou 评论0 收藏0
  • PHP之string之str_pad()函数使用

    摘要:使用另一个字符串填充字符串为指定长度该函数返回被从左端右端或者同时两端被填充到制定长度后的结果。如果的值是负数,小于或者等于输入字符串的长度,不会发生任何填充,并会返回。如果填充字符的长度不能被整除,那么可能会被缩短。 str_pad (PHP 4 >= 4.0.1, PHP 5, PHP 7) str_pad — Pad a string to a certain length w...

    qpwoeiru96 评论0 收藏0
  • [LintCode] Remove Node in Binary Search Tree [理解BS

    Problem Given a root of Binary Search Tree with unique value for each node. Remove the node with given value. If there is no such a node with given value in the binary search tree, do nothing. You sho...

    陈江龙 评论0 收藏0
  • [LintCode/LeetCode] Flatten Binary Tree to Linked

    Problem Flatten a binary tree to a fake linked list in pre-order traversal.Here we use the right pointer in TreeNode as the next pointer in ListNode. Example 1 1 ...

    TNFE 评论0 收藏0

发表评论

0条评论

X1nFLY

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<