leetcode - ZigZag Conversion

本文介绍了一种将字符串以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"

Zigzag:即循环对角线结构(

0       8       16      
1     7 9     15 17      
2   6   10   14   18      
3 5     11 13     19      
4       12       20      

 nRows行,声明nRows个字符串,每个字符串存储自己行的字符

向下循环:nRows

斜角线向上循环: 从nRows-2 开始,1 结束    (减去首尾两个端点)

重复

...

1
2
3
4
5
6
7
8
9
10
11
12
13
string convert(string s, int nRows){
    if(nRows == 1) return s;
    string res[nRows];
    int i = 0, j, gap = nRows-2;
    while(i < s.size()){
        for(j = 0; i < s.size() && j < nRows; ++j) res[j] += s[i++];//垂直向下循环
        for(j = gap; i < s.size() && j > 0; --j) res[j] += s[i++];//向上循环
    }
    string str = "";
    for(i = 0; i < nRows; ++i)
        str += res[i];
    return str;
}

  

法二:

每次把由字母排列成的一个 V 形状 ,当一个循环,每个循环之间相差 2(numRows-1),如上面 Zigzag:即循环对角线结构 中的 0与8 相差2(5-1)

不同的行i 所有 对应的差值 就是 2(numRows-i -1),相当于行数减少了,减少到了numRows-i行。

注意:numRows小于2时,差值为0

java版本

public class Solution {
    public String convert(String s, int numRows) {
        if(s.length()<=2 || numRows<2)
            return s;
        String ret="";
        int distance=2*(numRows-1);
        for(int i=0;i<numRows;i++){
            for(int j=i;j<s.length();j=j+distance){
                ret=ret+s.charAt(j);
                if(i!=0 && i!=numRows-1 && j+ (distance-2*i) < s.length())
                   ret=ret+ s.charAt( j+ (distance-2*i) ) ;
            }
        }
        return ret;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值