瀏覽標籤:

C#

[C#][LeetCode][Easy] 535. Encode and Decode TinyURL

題目:

TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.
Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.

心得:

這題實務上的話我應該會用資料庫來存key,簡單易用不是嗎?
不過要小心的是不能使用流水號來當作tinyurl的參數,
這樣會有被猜出key的可能性,可能就隨機產生一個短的字串並檢查不能重複來當key

我的答案(轉base64):

public class Codec {

    // Encodes a URL to a shortened URL
    public string encode(string longUrl) {
        return Convert.ToBase64String(Encoding.UTF8.GetBytes(longUrl));
    }

    // Decodes a shortened URL to its original URL.
    public string decode(string shortUrl) {
        return Encoding.UTF8.GetString(Convert.FromBase64String(shortUrl));
    }
}

 

我的答案(guid):

public class Codec {
    
    private static Dictionary<string, string> dty = new Dictionary<string, string>();
    
    // Encodes a URL to a shortened URL
    public string encode(string longUrl) {
        string guid = Guid.NewGuid().ToString();
        dty.Add(guid, longUrl);
        return guid;
    }

    // Decodes a shortened URL to its original URL.
    public string decode(string shortUrl) {
        string url = string.Empty;
        return dty.TryGetValue(shortUrl, out url) ? url : null;
    }
}

 

       

[C#][LeetCode][Easy] 561. Array Partition I

問題:

Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), …, (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.

心得:
看到這題我第一個反應就是去找linq有沒有辦法分割陣列,然後再加總= =
不過LINQ效能沒有很好,看到最佳解答有提供一個不錯的方法。

我的答案:

public class Solution {
    public int ArrayPairSum(int[] nums) {
        return nums.OrderBy(x => x)
                   .Select((x, index) => new { index, x })
                   .GroupBy(x => x.index / 2)
                   .Sum(x => x.Select(y => y.x).Min());
    }
}

最佳解答:

public class Solution {
    public int ArrayPairSum(int[] nums) {
        Array.Sort(nums);
        int result = 0;
        for (int i = 0; i < nums.Length; i += 2)
        {
            result += nums[i];
        }
        return result;
    }
}
       

[C#][Linq][Expression] 將陣列分割成固定長度的小陣列

來源:[Snippet]在C#中将List分割成多个定长的小List

可以將一個很長很長很長的List分割成固定大小的List方便批次運算。

程式碼:

public static IEnumerable<IEnumerable<T>> ChunkBy<T>(this IEnumerable<T> source, int chunkSize)
{
    return source.Select((x, i) => new { Index = i, Value = x }).GroupBy(x => x.Index / chunkSize).Select(x => x.Select(v => v.Value));
}
       

[C#][LeetCode][Easy] 617. Merge Two Binary Trees

問題:

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.

心得:

這題就是把兩個二元樹合併,我就想著最簡單遞迴來解決,看了最佳解答才發現如果為一邊null的話就可以直接用另外一邊來return更有效率,學習了。
我的答案:

public class Solution {
    public TreeNode MergeTrees(TreeNode t1, TreeNode t2) {
        if (t1 == null && t2 == null)
        {
            return null;
        }

        int t1Val = (t1 == null) ? 0 : t1.val;
        int t2Val = (t2 == null) ? 0 : t2.val;

        return new TreeNode(t1Val + t2Val)
        {
            left = MergeTrees(t1?.left, t2?.left),
            right = MergeTrees(t1?.right, t2?.right)
        };
    }
}

最佳解答:

public class Solution {
    public TreeNode MergeTrees(TreeNode t1, TreeNode t2) {
        if (t1 == null)
        {
            return t2;
        }
        if (t2 == null)
        {
            return t1;
        }

        return new TreeNode(t1.val + t2.val)
        {
            left = MergeTrees(t1.left, t2.left),
            right = MergeTrees(t1.right, t2.right)
        };
    }
}

 

       

[C#] Invoke 與 BeginInvoke 在主副線程中的執行順序和區別

在寫多執行緒時必須更新UI狀態時查到的資料,做個紀錄一下。

據msdn中介紹,它們最大的區別就是BeginInvoke屬於異步執行的。

  • Control.Invoke 方法 (Delegate)
    在擁有此控件的基礎窗口句柄的線程上執行指定的委託。
  • Control.BeginInvoke 方法 (Delegate)
    在創建控件的基礎句柄所在線程上異步執行指定委託。

總結:

以下為了方便理解,假設如下:

  1. 主線程表示Control.Invoke或Control.BeginInvoke中Control所在的線程,即創建該創建的線程。 (一般為UI線程)
  2. 支線程表示不同於主線程的調用Invoke或BeginInvoke的線程。
  3. Control的Invoke和BeginInvoke的委託方法是在主線程,即UI線程上執行。 (也就是說如果你的委託方法用來取花費時間長的數據,然後更新界面什麼的,千萬別在主線程上調用Control.Invoke和Control.BeginInvoke,因為這些是依然阻塞UI線程的,造成界面的假死)
  4. Invoke會阻塞主支線程,BeginInvoke只會阻塞主線程,不會阻塞支線程!因此BeginInvoke的異步執行是指相對於支線程異步,而不是相對於主線程異步。 (從最後一個例子就能看出,程序運行點擊button1)

 

轉載:【分析】浅谈C#中Control的Invoke与BeginInvoke在主副线程中的执行顺序和区别(SamWang)

       

[C#][ASP.NET MVC5] 用 Global.asax 的 Application_Error 來記錄 Exception

當網站出錯時有問題卻沒有紀錄怎麼辦?用Application_Error來Hold住全場吧 !!

  • Global.asax
    protected void Application_Error(object sender, EventArgs e)
    {
    	var rawUrl = Request.RawUrl;
    	var ex = Server.GetLastError();
    	Debug.WriteLine("RawUrl: {0}", rawUrl);
    	Debug.WriteLine("Ex: {0}", ex.Message);
    	Debug.WriteLine("StackTrace: {0}", ex.StackTrace);
    
    	//若網頁沒有撰寫任何的錯誤處理,或是沒有回收清除(Server.ClearError),最後將顯示預設錯誤畫面;反之若有清除則不再往下一個除錯流程。
    	Server.ClearError();
    
    	//導回首頁
    	Response.Redirect("/");
    }

轉載:[ASP.NET] 追蹤與除錯 / Trace and Debug (二)

       

[C#][ASP.NET MVC5][Autofac] DI Framework – AutofacConfig.cs

之前嘗試很多次都失敗,這次終於成功註冊Controller、Service與Repository了,來記錄一下設定檔。

  • AutofacConfig.cs
    /// <summary>
    /// DI設定檔
    /// </summary>
    public class AutofacConfig
    {
    	/// <summary>
    	/// 註冊DI注入物件資料
    	/// </summary>
    	public static void Register()
    	{
    		// 容器建立者
    		ContainerBuilder builder = new ContainerBuilder();
    
    		// 註冊Controllers
    		builder.RegisterControllers(Assembly.GetExecutingAssembly());
    
    		// 註冊Service
    		builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
    			   .Where(t => t.Name.EndsWith("Service"))
    			   .AsSelf();
    
    		// 註冊Repository
    		builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
    			   .Where(t => t.Name.EndsWith("Repository"))
    			   .AsSelf();
    
    		// 建立容器
    		IContainer container = builder.Build();
    
    		// 解析容器內的型別
    		AutofacDependencyResolver resolver = new AutofacDependencyResolver(container);
    
    		// 建立相依解析器
    		DependencyResolver.SetResolver(resolver);
    	}
    }
  • Global.asax
    protected void Application_Start()
    {
        //加入這行
        AutofacConfig.Register();
    }
       

[C#] (免安裝)WMIScan v1.0 檢查是否有奇怪的腳本(hao123)

前提摘要:[Windows] 瀏覽器首頁被 hao123 綁架

我寫了一隻小程式可以檢查WMI裡面是否有奇怪的Script在排程,並顯示出怪異的Script讓使用者決定是否刪除

操作步驟:

  1. 下載 https://github.com/shuangrain/WMIScan/releases/download/v1.0/WMIScan.zip
  2. 解壓縮後開啟WMIScan.exe
  3. 點擊Scan後會在下方Show出可疑的Script
  4. 點選可疑的Script後點擊右邊的刪除
  5. 之後再清除有問題的lnk檔就沒問題囉 !!

 

GitHub:https://github.com/shuangrain/WMIScan

       

[C#][LeetCode][Easy] 167. Two Sum II – Input array is sorted

心得

這題我本來是想用兩個for迴圈解決的

public class Solution {
    public int[] TwoSum(int[] numbers, int target) {
        for (int i = 0; i < numbers.Length; i++)
        {
            for (int j = numbers.Length - 1; j > i; j--)
            {
                if (numbers[i] + numbers[j] == target)
                {
                    return new int[] { i + 1, j + 1 };
                }
            }
        }

        throw new Exception();
    }
}

但發現會Time Limit Exceeded於是乎看了一下Solutions他們是用一個while迴圈來解答,題目要求index1<index2且不能使用重複的元素,所以這題如果用while的話宣告兩個變數分別是left與right就可以只用一個迴圈就解決。

問題

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

答案

public class Solution {
    public int[] TwoSum(int[] numbers, int target) {
        int left = 0;
        int right = numbers.Length - 1;
        while (numbers[left] + numbers[right] != target)
        {
            if (numbers[left] + numbers[right] > target)
            {
                right--;
            }
            else
            {
                left++;
            }
        }

        return new int[] { left + 1, right + 1 };
    }
}

 

       

[C#][LeetCode][Easy] 409. Longest Palindrome

心得

獲得字串並判斷字串內的字母能組成最長的回文大小為多少,例如傳入asdasdAAAvzxh則答案為9,字串為asdAvAdsa,其中v可替換成任意一位使用字母。

問題

Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.

This is case sensitive, for example "Aa" is not considered a palindrome here.

Note:
Assume the length of given string will not exceed 1,010.

Example:

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

答案

public class Solution {
    public int LongestPalindrome(string s) {
        int ans = 0;
        int[] lower = new int[26];
        int[] upper = new int[26];
        foreach (var item in s)
        {
            if (item > 'Z')
            {
                lower[item - 'a']++;
            }
            else
            {
                upper[item - 'A']++;
            }

        }
        for (int i = 0; i < lower.Length; i++)
        {
            ans += lower[i] / 2;
            ans += upper[i] / 2;
        }

        ans = ans * 2;
        return ans < s.Length ? ans + 1 : ans;
    }
}