Maximum Length of Subarray With Positive Product - Leet Code Solution
Problem Statement Maximum Length of Subarray With Positive Product. Given an…
August 27, 2019
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:
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
If you look the pattern, its going in two directions:
You need one flag to indicate whether you are going downward or going upward.
public class Q6_ZigZagConversion {
private String str;
public Q6_ZigZagConversion(String str) {
this.str = str;
}
public String conversion(int numRows) {
int l = this.str.length();
List<StringBuffer> zigzag = new ArrayList<StringBuffer>();
for (int i=0; i<numRows; i++) {
zigzag.add(new StringBuffer());
}
boolean comingFromTop = true;
int zig = 0;
for (int i=0; i<l; i++) {
zigzag.get(zig).append(this.str.charAt(i));
if (zig == numRows-1) {
comingFromTop = false;
}
else if (zig == 0) {
comingFromTop = true;
}
zig = comingFromTop ? zig + 1 : zig - 1;
zig = zig % numRows;
}
StringBuffer sb = new StringBuffer();
for (int i=0; i<numRows; i++) {
sb.append(zigzag.get(i));
}
return sb.toString();
}
}
Problem Statement Maximum Length of Subarray With Positive Product. Given an…
Problem Statement There are two sorted arrays nums1 and nums2 of size m and n…
Introduction I will list some of the interesting usage of bitwise operators…
This algorithm is very useful for large input. And, is quite efficient one. It…
Problem Statement Given two strings s and t , write a function to determine if t…
Here are some tips while giving your coding interviews. 1. Never try to jump to…
In this post, we will see some of the frequently used concepts/vocabulary in…
System design interview is pretty common these days, specially if you are having…
Introduction You are given an array of integers with size N, and a number K…
Graph Topological Sorting This is a well known problem in graph world…
Problem Statement Given a Binary tree, print out nodes in level order traversal…
Problem Statement Given an array nums of n integers and an integer target, are…