[LeetCode]006. ZigZag Conversion

本文介绍了一种将字符串按Z形模式排列并重新读取的方法。给出一个字符串和行数,文章提供了一个Java解决方案,用于计算字符串中字符的数学关系,并实现了指定行数下字符串的Z形转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R
And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".


Solution:

find the mathematical relations of characters in the string.

the distance between each red character (such as "A" to "L")in same row is 2*(nRows-1);

there is at most one intermediate char in two red chars, the distance from A to P is 2*(nRows- 1- i), i is the current row number(from 0 to nRows);


刚开始没有看清题目,当成只有3行来解了。

画出nRows=4, nRows=5时的图,总结出数学关系求解即可。

注意边界条件,否则无法通过OJ(漏写了nRwos为1时的情况)。


public class Solution {
    public String convert(String s, int nRows) {
        // Start typing your Java solution below
        // DO NOT write main() function
       if(s==null){
           return null;
       }
       int len = s.length();
       // must consider the bounday conditions.
       if(nRows <= 1){
           return s;
       }
       StringBuffer sb = new StringBuffer();
       for(int i=0; i<nRows; i++){
           int j = i;
           while(j<len){
               sb.append(s.charAt(j));
               if(i%(nRows-1) != 0){
                   int k= j + 2*(nRows-1-i);
                   //use k as an "intermediate" between 2 characters in same horizontal line.
                   if(k<len){
                       sb.append(s.charAt(k));
                   }
               }
               
               j += 2*(nRows-1);
               //distance between the character which in the same horizontal line, 
               //but in different vertical lines.
           }
       }
       return sb.toString();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值