当前位置:  首页>> 技术小册>> 数据结构与算法(中)

难度: Medium

内容描述

  1. 字符串“PAYPALISHIRING”以之字形模式写入给定数量的行,如下所示:(您可能希望以固定字体显示此模式,以提高可读性)
  2. P A H N
  3. A P L S I I G
  4. Y I R
  5. And then read line by line: "PAHNAPLSIIGYIR"
  6. Write the code that will take a string and make this conversion given a number of rows:
  7. string convert(string s, int numRows);
  8. Example 1:
  9. Input: s = "PAYPALISHIRING", numRows = 3
  10. Output: "PAHNAPLSIIGYIR"
  11. Example 2:
  12. Input: s = "PAYPALISHIRING", numRows = 4
  13. Output: "PINALSIGYAHRPI"
  14. Explanation:
  15. P I N
  16. A L S I G
  17. Y A H R
  18. P I

解题方案

思路 1
**- 时间复杂度: O(len(s))**- 空间复杂度: O(len(s))**

需要将字符串s转换为按N排列,总共有numRows行,直接将字符串转换为N字形,然后输出, beats 74.18%

  1. class Solution {
  2. // 将字符串进行z子排列,行数为numRows
  3. public String convert(String s, int numRows) {
  4. // 思路:先转换为z字
  5. List[] arr = new List[numRows]; // 保存每一行元素
  6. for(int i = 0; i < numRows; i ++){
  7. arr[i] = new ArrayList();
  8. }
  9. char[] chars = s.toCharArray();
  10. for(int i = 0; i < chars.length;){
  11. // 每次打印两列
  12. for(int j = 0; j < numRows && i < chars.length; j++,i++){
  13. List list = arr[j];
  14. list.add(chars[i]);
  15. }
  16. for(int j = numRows - 1; j >= 0 && i < chars.length; j --){
  17. if(j == numRows - 1 || j == 0){
  18. arr[j].add(' ');
  19. }else{
  20. arr[j].add(chars[i]);
  21. i++;
  22. }
  23. }
  24. }
  25. // 输出最终字符串
  26. char[] result = new char[chars.length];
  27. int index = 0;
  28. for(int i = 0; i < numRows; i ++){
  29. List list = arr[i];
  30. for(int j = 0; j < list.size(); j ++){
  31. if(' ' != (char)list.get(j)){
  32. result[index++] = (char) list.get(j);
  33. }
  34. }
  35. }
  36. return new String(result);
  37. }
  38. }

该分类下的相关小册推荐: