当前仓库属于关闭状态,部分功能使用受限,详情请查阅 仓库状态说明
1 Star 0 Fork 1

wwmin / wwm.leetcode.helper
关闭

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

wwm.LeetCodeHelper

wwm.LeetCodeHelper wwm.LeetCodeHelper GitHub license

仓库地址:https://gitee.com/wwmin/wwm.leetcode.helper

1. 说明

wwm.LeetCodeHelper是一款帮助在本地用C#做LeetCode题的一个库,具有自动拉取题生成csharp文件,自动生成测试用例,自动完成测试对比等等的功能。

  • 适用语言范围:C#
  • 使用LeetCode版本:国内版

2. 安装

dotnet add package wwm.LeetCodeHelper
Install-Package wwm.LeetCodeHelper

3. 使用方式

创建控制台应用程序

3.1 创建项目步骤

新建一个文件夹,然后cmd到此文件夹路径执行如下命令

//新建项目
dotnet new console
//添加leetcode帮助依赖
dotnet add package wwm.leetcodehelper
//添加操作配置文件依赖
dotnet add package Microsoft.Extensions.Configuration
dotnet add package Microsoft.Extensions.Configuration.UserSecrets
//初始化用户机密文件
dotnet user-secrets init
//将web端的LEETCODE_SESSION cookie设置到机密文件,如下
dotnet user-secrets set "cookie_login:LEETCODE_SESSION" "your cookie"
//查看已添加的机密信息
dotnet user-secrets list
//查看package list
dotnet list package
//更新pacakge ,指定version
dotnet add package wwm.leetcodehelper -v 0.10.0
//安装依赖包
dotnet restore

3.2 添加.gitignore 文件

.vs/
bin/
obj/
/content
cookies.txt

只需要创建一次此控制台应用程序,后面的题库内容都是一个一个类文件 在program.cs文件中添加如下内容


using Microsoft.Extensions.Configuration;

#region 初始化
using Microsoft.Extensions.Configuration;

#region 初始化
#if false
//方法一: 直接明文保存LEETCODE_SESSION
var LEETCODE_SESSION = "";
#endif
// 使用本地机密文件secrets.json 然后从机密中读取登录信息, 此方法更好的保护自己的账号
//方法二: 使用vs IDE
//步骤1: 添加依赖 Microsoft.Extensions.Configuration
//步骤2: vs中右键项目然后选择管理用户机密,然后在打开的secrets.json中添加
/*
{
  "cookie_login": {
    "LEETCODE_SESSION": "your leetcode_session cookie",
  }
}
*/
//方法三: 使用dotnet cli
//步骤1: 添加依赖 Microsoft.Extensions.Configuration
//步骤2: 启用机密,使用.net cli命令 `dotnet user-secrets init`
//步骤3: 设置机密, `dotnet user-secrets set "cookie_login:LEETCODE_SESSION" "your cookie"`
//步骤4: 查看 `dotnet user-secrets list`
// 更多dotnet cli 可参考:https://docs.microsoft.com/zh-cn/aspnet/core/security/app-secrets?view=aspnetcore-6.0&tabs=windows
var config = new ConfigurationBuilder().SetBasePath(AppDomain.CurrentDomain.BaseDirectory).AddUserSecrets<Program>().Build();
var LEETCODE_SESSION = config.GetSection("cookie_login:LEETCODE_SESSION")?.Value;
if (!string.IsNullOrEmpty(LEETCODE_SESSION)) await LeetCodeHelper.InitAsync(LEETCODE_SESSION);
else throw new Exception("请传入LEETCODE_SESSION");
#endregion

//1. 传入url或titleSlug获取题目
//2. 传入题号获取题目
//3. 参数为空时获取当天的每日一题
//如果已获取题目则会自动开始测试
await LeetCodeHelper.Run();

Console.Write("按任意键退出...");
Console.ReadKey();

4. 初始化用户信息

为了安全起见,建议用户将自己的cookie LEETCODE_SESSION值存储到secrets.json文件中,这样将自己的代码库上传到git远程仓库就不会担心自己的leet-code信息被盗取了

具体说明:参考上段代码中的注释部分

如何获取LEETCODE_SESSION?

获取leetcode网站cookie方法: 登录leetcode网站后,打开控制台,找到控制台的Application面板在左侧的Storage项中找到Cookies然后选中https://leetcode.cn 右侧有出现该网站的cookie目录,寻找到LEETCODE_SESSION选中后,复制后面的Value值即可。

5. 刷题方式:1.自定义url 2.每日一题

5.1 自定义url

将自己想要刷的题目的url粘贴到program.cs文件中的url变量中,然后运行程序即可,程序会自动获取题目. 如果此题已经存在在本地, 则会开启测试模式.

5.2 每日一题模式

自动获取当天的每日一题,如果此题已经存在本地, 则会开启测试模式

5.3 自定义题号

将自己想要刷的题目的题号粘贴到program.cs文件中的questionId变量中,然后运行程序即可,程序会自动获取题目. 如果此题已经存在在本地, 则会开启测试模式.

6. 获取题目

在选择自定义url模式刷题时,获取题目需要添加url内容

string url = "https://leetcode.cn/problems/two-sum/"

然后F5运行, 控制台中内容如下:

已从接口获取数据
将数据写入文件:two-sum.txt
文件已写入:D:\work\learn\dotnet\wwm.LeetCodeHelper\wwm.LeetCodeHelper.Test\Content\two-sum.txt
文件名已拷贝到剪贴板: two-sum.txt
文件已写入:D:\work\learn\dotnet\wwm.LeetCodeHelper\wwm.LeetCodeHelper.Test\Solutions\two-sum.cs
文件名已拷贝到剪贴板: two-sum.cs
按任意键退出...

文件名已经复制到了剪贴板中,在Visual Studio中按Ctrl+Shift+T快捷键弹出框中,粘贴文件名后查找到回车即可,此处为了节省文件变多后查找刚下载的文件的时间

内容如下:

namespace Solutions;
/// <summary>
/// 1556. 通过翻转子数组使两个数组相等
/// difficulty: Easy
/// </summary>
public class CanBeEqualSolution : ITest
{
    private class Data : DataAttribute
    {
        public override IEnumerable<object[]> GetData()
        {
            yield return new object[] { StringTo<int[]>("[1,2,3,4]").ToArray(), StringTo<int[]>("[2,4,1,3]").ToArray(), true };
            yield return new object[] { StringTo<int[]>("[7]").ToArray(), StringTo<int[]>("[7]").ToArray(), true };
            yield return new object[] { StringTo<int[]>("[3,7,9]").ToArray(), StringTo<int[]>("[3,7,11]").ToArray(), false };
        }
    }

    [Data]
    public bool CanBeEqual(int[] target, int[] arr)
    {
        return default;
    }
}

会在题内容上面加上测试用例, 如果是自定义刷题模式时,将url置空后就会进入执行实现ITest接口的类, 如果是每日刷题,会自动判断题目是否已经下载,如果已下载则进入执行实现ITest的接口类。

7. 配置vscode debug环境

如果使用visual studio跳过此步骤, 如果使用vscode则需要安装vscode插件 C#

8. 配置launch.json 和 tasks.json

如果使用visual studio跳过此步骤, 如果使用vscode则需要配置launch.json 和 tasks.json 按F5 在下拉的选择环境框中选择 .NET5+ and .NET Core 此时会创建launch.json,注意此时要修改configurations:program 下的参数: 将"${workspaceFolder}/bin/Debug/<insert-target-framework-here>/<insert-project-name-here>.dll", 中的<insert-target-framework-here>修改为你自己的net6.0或这你自己的版本(此处推荐最新的net6.0), 然后修改<insert-project-name-here>为你自己的项目名称,如我自己的leetcode_test, 然后将configurations:console换成integratedTerminal. 此时再在Program.cs文件下按F5,应该会弹出 Count not find the task 'build'警告框,此时选择Configure Task按钮 然后在弹出选择框中选择Create task.json file from template,然后再在弹出的选择框中选择.NET Core.此时就在.vscode文件夹中创建好了tasks.json

9. 运行测试

编写你的算法代码

using wwm.LeetCodeHelper.Servers;

namespace Solutions;
/// <summary>
/// 1. 两数之和
/// https://leetcode.cn/problems/two-sum/
/// difficulty: Easy
/// </summary>
public class TwoSumSolution : ITest
{
    private class Data : DataAttribute
    {
        public Data()
        {
            IgnoreOrder = true;
        }

        public override IEnumerable<object[]> GetData()
        {
            yield return new object[] { StringTo<int[]>("[2,7,11,15]").ToArray(), 9, StringTo<int[]>("[0,1]").ToArray() };
            yield return new object[] { StringTo<int[]>("[3,2,4]").ToArray(), 6, StringTo<int[]>("[1,2]").ToArray() };
            yield return new object[] { StringTo<int[]>("[3,3]").ToArray(), 6, StringTo<int[]>("[0,1]").ToArray() };
        }
    }

    [Data]
    public int[] TwoSum(int[] nums, int target)
    {
        int[] o = new int[2];
        int i, j, k = 0;
        for (i = 0; i < nums.Length; i++)
        {
            for (j = i + 1; j < nums.Length; j++)
            {
                if ((nums[i] + nums[j]) == target)
                {
                    o[0] = i;
                    o[1] = j;
                    k = 1;
                }
            }
            if (k == 1) break;

        }
        return o;
    }
}

F5执行,结果如下:

------->TwoSumSolution
TwoSum: 执行结果正确: [0,1]
TwoSum: 执行结果正确: [1,2]
TwoSum: 执行结果正确: [0,1]
_______测试结果: 3/3 ,耗时:97ms________

按任意键退出...

如果执行中有错误答案,会给出预期值和运行结果值,如下

------->TwoSumSolution
TwoSum: 执行结果正确: [0,1]
TwoSum: 执行结果错误.
  预期值:[1,2]
  结果值:[0,0]
TwoSum: 执行结果正确: [0,1]
_______测试结果: 2/3 ,耗时:82ms________

按任意键退出...

控制台中也会有颜色提示,正确的为绿色,错误的为红色。

当测试完成后,需要将类的继承ITest去掉,这样下次就不会测试该类了。

该库暂时仍在完善中,如遇到问题可提issue。

10. 计划/TODO

  1. 实现一个可视化树结构的功能

11. 编译错误解答

问题1: 如果出现了如下错误

Exception has occurred: CLR/System.InvalidOperationException
“System.InvalidOperationException”类型的异常在 System.Console.dll 中发生,但未在用户代码中进行处理: 'Cannot read keys when either application does not have a console or when console input has been redirected. Try Console.Read.'

可将launch.json文件下的configurations:console换成integratedTerminal,或者删除Program.cs文件中的Console.ReadKey();这行代码

问题2: 如果出现了如下错误

“Microsoft.Playwright.PlaywrightException”类型的异常在 System.Private.CoreLib.dll 中发生,但未在用户代码中进行处理: 'Chromium distribution 'chrome' is not found at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
Run "playwright install chrome"'

需要安装playwright, 前往playwright官网 执行

# Install required browsers
pwsh bin\Debug\netX\playwright.ps1 install

mac 下执行pwsh时会出现bash: pwsh: command not found则需要下载安装powershell,地址https://github.com/PowerShell/PowerShell/releases 选择合适的系统下载安装,然后再次执行

# Install required browsers
pwsh bin\Debug\netX\playwright.ps1 install
# max下 \ 应变成 /

如果出现

Unhandled exception. Microsoft.Playwright.PlaywrightException: Chromium distribution 'chrome' is not found at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
Run "playwright install chrome"
   at Microsoft.Playwright.Transport.Connection.SendMessageToServerAsync[T](String guid, String method, Object args)

则需要执行

playwright install chrome

12. 相关连接

13. 许可证 / License

wwm.LeetCodeHelper 采用 Apache License 2.0 开源许可证。

wwm.LeetCodeHelper uses the Apache License 2.0 open source license.

作者:wwmin 微信公众号: DotNet技术说 本文链接:https://www.jianshu.com/p/b038e21032ab 评论和私信会在第一时间回复。转载请注明出处! 如果您觉得文章对您有帮助,关注点赞,您的鼓励是博主的最大动力!

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

leetcode c#答题代码自动生成器 展开 收起
C#
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
C#
1
https://gitee.com/wwmin/wwm.leetcode.helper.git
git@gitee.com:wwmin/wwm.leetcode.helper.git
wwmin
wwm.leetcode.helper
wwm.leetcode.helper
master

搜索帮助