Skip to main content

【LeetCode 6】Z 字形变换

·83 words·1 min
WFUing
Author
WFUing
A graduate who loves coding.

class Solution {
    public String convert(String s, int numRows) {
        if(numRows < 2) return s;
        List<StringBuilder> rows = new ArrayList<StringBuilder>();
        for(int i = 0; i < numRows; i++) rows.add(new StringBuilder());
        int i = 0, flag = -1;
        for(char c : s.toCharArray()) {
            rows.get(i).append(c);
            if(i == 0 || i == numRows -1) flag = - flag;
            i += flag;
        }
        StringBuilder res = new StringBuilder();
        for(StringBuilder row : rows) res.append(row);
        return res.toString();
    }
}

string 的操作

  • substring(0, i)
  • trim()
  • split('\\s+)
  • join(' ', wordlist)
  • Collections.reverse(wordlist)