網站首頁 編程語言 正文
Z字形變換
描述
將一個給定字符串 s 根據給定的行數 numRows ,以從上往下、從左到右進行 Z 字形排列。
比如輸入字符串為 “PAYPALISHIRING” 行數為 3 時,排列如下:
P A H N
A P L S I I G
Y I R
之后,你的輸出需要從左往右逐行讀取,產生出一個新的字符串,比如:“PAHNAPLSIIGYIR”。
請你實現這個將字符串進行指定行數變換的函數:
string convert(string s, int numRows);
示例1
輸入:s = "PAYPALISHIRING", numRows = 3
輸出:"PAHNAPLSIIGYIR"
示例2
輸入:s = "PAYPALISHIRING", numRows = 4
輸出:"PINALSIGYAHRPI"
解釋:
P ? ? I ? ?N
A ? L S ?I G
Y A ? H R
P ? ? I
示例3
輸入:s = "A", numRows = 1
輸出:"A"
思路/解法
模擬法,根據所給條件,線性處理即可(Z字形存在一定規律,每當固定的條件后前進方向進行轉變)。
class Solution {
public:
string convert(string s, int numRows) {
int rows = numRows;
int columns = ((s.length() / (2 * rows - 1)) + 1) * rows;//盡可能縮小所使用的空間,這里columns可優化,并未精確求解
std::vector<std::vector<char>> arrs(rows, std::vector<char>(columns));
//初始化
for (int i = 0; i < rows; i++)
for (int j = 0; j < columns; j++)
arrs[i][j] = '0';
int x = 0, y = 0;
int index = 0;
while (index < s.length())
{
if (index < s.length() && x < rows)
arrs[x++][y] = s[index++];
if (index < s.length() && x == rows)
{
//更新x和y
y++;
x -= 2;
while (index < s.length() && x > 0)
arrs[x--][y++] = s[index++];
x = 0;//重置x
}
}
std::string res;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
if (arrs[i][j] != '0' && arrs[i][j] != '\0')
res.push_back(arrs[i][j]);
}
}
return res;
}
};
原文鏈接:https://blog.csdn.net/qq135595696/article/details/125687072
相關推薦
- 2022-04-12 iOS SDK中引入第三方頭文件報Undefined symbols for architectur
- 2022-10-14 面試官:int(1) 和 int(10) 有什么區別?
- 2022-02-09 Qt5連接并操作PostgreSQL數據庫的實現示例_C 語言
- 2023-12-10 記錄一次導出Excel報表的錯誤
- 2024-01-27 ioc,ioc實際運用
- 2022-08-19 淺談Redis6.x io事件驅動模型
- 2022-04-23 一起來了解python的基本輸入和輸出_python
- 2022-06-15 C#實現冒泡排序和插入排序算法_C#教程
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支