diff options
| author | crupest <crupest@outlook.com> | 2020-05-07 23:17:16 +0800 | 
|---|---|---|
| committer | crupest <crupest@outlook.com> | 2020-05-07 23:17:16 +0800 | 
| commit | a3a2519a087f710c8820d94584648aaba75528d7 (patch) | |
| tree | 4f91801efa8d37a11c3af1500d9dc984f5b54510 | |
| parent | 5b3584fcc79c87f87edebbf08f2f9c144f298eed (diff) | |
| download | crupest-a3a2519a087f710c8820d94584648aaba75528d7.tar.gz crupest-a3a2519a087f710c8820d94584648aaba75528d7.tar.bz2 crupest-a3a2519a087f710c8820d94584648aaba75528d7.zip | |
import(solutions): Add problem 6 .
| -rw-r--r-- | works/solutions/.gitignore | 1 | ||||
| -rw-r--r-- | works/solutions/cpp/.gitignore | 1 | ||||
| -rw-r--r-- | works/solutions/cpp/6.cpp | 56 | 
3 files changed, 58 insertions, 0 deletions
| diff --git a/works/solutions/.gitignore b/works/solutions/.gitignore new file mode 100644 index 0000000..600d2d3 --- /dev/null +++ b/works/solutions/.gitignore @@ -0,0 +1 @@ +.vscode
\ No newline at end of file diff --git a/works/solutions/cpp/.gitignore b/works/solutions/cpp/.gitignore new file mode 100644 index 0000000..adb36c8 --- /dev/null +++ b/works/solutions/cpp/.gitignore @@ -0,0 +1 @@ +*.exe
\ No newline at end of file diff --git a/works/solutions/cpp/6.cpp b/works/solutions/cpp/6.cpp new file mode 100644 index 0000000..f1d947c --- /dev/null +++ b/works/solutions/cpp/6.cpp @@ -0,0 +1,56 @@ +#include <string>
 +#include <iostream>
 +
 +using std::string;
 +
 +class Solution
 +{
 +public:
 +    string convert(string s, int numRows)
 +    {
 +        if (numRows == 1)
 +            return s;
 +
 +        const auto length = s.size();
 +        const int count_per_group = numRows * 2 - 2;
 +        string result;
 +        result.reserve(length);
 +        for (int row = 0; row < numRows; row++)
 +        {
 +            if (row == 0)
 +            {
 +                for (int p = 0; p < length; p += count_per_group)
 +                    result += s[p];
 +            }
 +            else if (row == numRows - 1)
 +            {
 +                for (int p = row; p < length; p += count_per_group)
 +                    result += s[p];
 +            }
 +            else
 +            {
 +                bool former = true;
 +                const auto former_gap = count_per_group - row * 2;
 +                const auto latter_gap = count_per_group - former_gap;
 +                for (int p = row; p < length; p += (former ? former_gap : latter_gap), former = !former)
 +                    result += s[p];
 +            }
 +        }
 +        return result;
 +    }
 +};
 +
 +int main()
 +{
 +    Solution s;
 +
 +    auto result1 = s.convert("PAYPALISHIRING", 3);
 +    auto result2 = s.convert("PAYPALISHIRING", 4);
 +    std::cout
 +        << s.convert("A", 1) << '\n'
 +        << result1 << '\n'
 +        << "PAHNAPLSIIGYIR\n"
 +        << result2 << '\n'
 +        << "PINALSIGYAHRPI\n";
 +    return 0;
 +}
\ No newline at end of file | 
