[C#][LeetCode][Easy] 242. Valid Anagram

心得:

這題要比較兩個字串是否具有相同字母(不管順序),因為這題比較簡單,所以就嘗試用了許多方式解答。

問題:

Given two strings s and t, write a function to determine if t is an anagram of s.

For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.

Note:
You may assume the string contains only lowercase alphabets.

答案:

  • LinQ – OrderBy
    public class Solution {
        public bool IsAnagram(string s, string t) {
            return new string(s.OrderBy(x => x).ToArray()) == new string(t.OrderBy(x => x).ToArray());
        }
    }
  • LinQ – Sort
    public class Solution {
        public bool IsAnagram(string s, string t) {
            var arr_1 = s.ToList();
            var arr_2 = t.ToList();
            arr_1.Sort();
            arr_2.Sort();
            return new string(arr_1.ToArray()) == new string(arr_2.ToArray());
        }
    }
  • Normal – Array.Sort
    public class Solution {
        public bool IsAnagram(string s, string t) {
            var arr_1 = s.ToArray();
            var arr_2 = t.ToArray();
            Array.Sort(arr_1);
            Array.Sort(arr_2);
            return new string(arr_1) == new string(arr_2);
        }
    }
  • Normal – 硬幹 (會 Time Limit Exceeded)
    public class Solution {
        public bool IsAnagram(string s, string t) {
            return Sort(s) == Sort(t);
        }
        
        private string Sort(string str){
            string result = "";
             for(int i = 0; i < 25; i++){
                char c = Convert.ToChar(Convert.ToInt16('a') + i);
                for(int j = 0; j < str.Length; j++){
                    if(c == str[j]){
                        result += c;
                    }
                }
            }
            
            return result;
        }
    }

參考:

  1. (C#)用迴圈印出字母A到Z
       

[C#][LeetCode][Easy] 292. Nim Game

心得:

一次可以拿1~3顆石頭,最後一個把石頭拿完的人就算勝利,很簡單的一支小程式判斷是否可以贏得這場遊戲,而且有先手優勢,所以只要是除不滿4就一定會贏。

問題:

You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.

Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.

For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.

Hint:

If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?

答案:

public class Solution {
    public bool CanWinNim(int n) {
        if(n < 4){
            return true;
        }
        else{
            return n % 4 > 0;
        }
    }
}

 

       

[C#][LeetCode][Easy] 448. Find All Numbers Disappeared in an Array

心得:

題目大意是有一陣列1~N且亂序,必須找出N並找出未出現哪些數字,剛開始我用硬幹的方式,結果顯示Time Out如下:

public class Solution {
    public IList<int> FindDisappearedNumbers(int[] nums) {
        List<int> ans = new List<int>();
        
        if(nums.Length > 1){
            //Sort
            for(int i = 0; i < nums.Length; i++){
                for(int j = i; j < nums.Length; j++){
                    if(nums[j] < nums[i]){
                        int tmp = nums[j];
                        nums[j] = nums[i];
                        nums[i] = tmp;
                    }
                }
            }
            
            int n = nums.Length;
            for(int i = 0; i < n; i++){
                bool b = false;
                for(int j = 0; j < nums.Length; j++){
                    if(i+1 == nums[j]){
                        b = true;
                        break;
                    }
                }
                
                if(!b){
                    ans.Add(i+1);
                }
            }
        }else if(nums.Length == 1){
            if(nums[0] != 1){
                ans.Add(1);
            }
        }
        
        return ans;
    }
}

後來改用稍為聰明一點的LinQ來找出N,結果還是Time Out如下:

public class Solution {
    public IList<int> FindDisappearedNumbers(int[] nums) {
        List<int> ans = new List<int>();
        if(nums.Length > 0){
            int max = nums.Max();
            if(max < nums.Length){
                max = nums.Length;
            }
            for(int i = 1; i <= max; i++){
                if(nums.Any(x=> x == i) == false){
                    ans.Add(i);
                }
            }
        }
        
        return ans;
    }
}

最後生氣了,直接全部都用LinQ,交給RangeExcept直接省略兩個迴圈並且順利解決!

問題:

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

答案:

public class Solution {
    public IList<int> FindDisappearedNumbers(int[] nums) {
        List<int> ans = new List<int>();
        
        if(nums.Length > 0){
            ans.AddRange(Enumerable
            .Range(1, nums.Length > nums.Max() ? nums.Length : nums.Max())
            .Except(nums));
        }
        
        return ans;
    }
}

參考:

  1. [C#] 對List&lt;T&gt;取交集、聯集及差集
       

[C#][LeetCode][Easy] 344. Reverse String

心得:

非常單純的一題,把字串反轉過來就好了,一開始我的Code如下:

public class Solution {
    public string ReverseString(string s) {
        string str = "";
        for(int i = 0; i < s.Length; i++){
            str = s[i] + str;
        }
        
        return str;
    }
}

結果最後一個測試沒過顯示Time Out,我才發現我完全沒有考慮到校能問題…

就算用StringBuilder依然不會過…

拜大神才發現原來有Array.Reverse這個方法可以用,而且又好維護 !太神辣!

問題:

Write a function that takes a string as input and returns the string reversed.

答案:

  1. Array.Reverse
    public class Solution {
        public string ReverseString(string s) {
            char[] arr = s.ToCharArray();
            Array.Reverse(arr);
            return new string(arr);
        }
    }
  2. LinQ
    public class Solution {
        public string ReverseString(string s) {
            return new string(s.Reverse().ToArray());
        }
    }

     

參考資料:

  1. Best way to reverse a string
  2. Property or indexer ‘string.this[int]’ cannot be assigned to — it’s read only
       

[C#][LeetCode][Easy] 387. First Unique Character in a String

心得:

題目要我們找出字串中第一個沒有重複的字母索引值,如找不到則回傳-1。

不知道是太久沒有寫程式了還是怎樣,這題我卡好久,最後偷喵了一下Top Solutions才發現原來這麼簡單,IndexOf這個方法可以找到從開始到結束的第一個字串,LastIndexOf方法則可以找到從結束到開始的第一個字串,若這兩個值相等的話不就代表著沒有重複嗎!

問題:

Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.

答案:

public class Solution {
    public int FirstUniqChar(string s) {
        for(int i = 0;i < s.Length; i++){
            if(s.IndexOf(s[i]) == s.LastIndexOf(s[i])){
                return i;
            }
        }
        
        return -1;
    }
}

 

       

[C#][LeetCode][Easy] 412. Fizz Buzz

心得:

這題也滿簡單用迴圈跑1~n,如果是3的的倍數則將Fizz加入陣列,5的倍數則將Buzz加入陣列,同時是3與5的倍數的話則將FizzBuzz加入陣列,其餘則加入i。

 

題目:

Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

答案:

public class Solution {
    public IList<string> FizzBuzz(int n) {
        List<string> ans = new List<string>();
        for(int i = 1 ; i <= n ; i++ ){
            if(i > 2){
                if(i % 3 == 0 && i % 5 == 0){
                    ans.Add("FizzBuzz");
                }else if(i % 3 == 0){
                    ans.Add("Fizz");
                }else if(i % 5 == 0){
                    ans.Add("Buzz");
                }else{
                    ans.Add(i.ToString());
                }
            }else{
                ans.Add(i.ToString());
            }
        }
        
        return ans;
    }
}

 

       

[C#][LeetCode][Easy] 1. Two Sum

心得:

滿基本的一題,只是我的方法有點爛XD

 

題目:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

答案:

public class Solution {
    public int[] TwoSum(int[] nums, int target) {
        for(int i = 0; i < nums.Length; i++){
            for(int j = i + 1 ; j < nums.Length; j++){
                if(nums[i] + nums[j] == target){
                    return new int[]{i, j};
                }
            }
        }
        
        throw new Exception("error");
    }
}

 

       

[C#][LeetCode][Easy] 461. Hamming Distance

心得:

剛開始看到題目的時候,突然發現我連Hamming Distance是什麼都不清楚,Google一下才知道,原來是把一數字轉成二進位,並依序比對是否相異,如101010與111010紅色標記的地方不一樣,則距離為一,有了起頭後就好解決了 !!

 

題目:

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

答案:

public class Solution {
    public int HammingDistance(int x, int y) {
        int ans = 0;
        string num_1 = Convert.ToString(x, 2);
        string num_2 = Convert.ToString(y, 2);
        if ( num_1.Length != num_2.Length ){
            if ( num_1.Length > num_2.Length ){
                int diff = num_1.Length - num_2.Length;
                for ( int i = 0 ; i < diff ; i++){
                    num_2 = "0" + num_2;
                }
            }else{
                int diff = num_2.Length - num_1.Length;
                for ( int i = 0 ; i < diff ; i++){
                    num_1 = "0" + num_1;
                }
            }
        }
        for( int i = 0 ; i < num_1.Length; i++ ){
            if( num_1[i] != num_2[i] ){
                ans++;
            }
        }
        
        return ans;
    }
}

 

 

參考網站:

  1. Hamming distance
  2. [C#] 轉2進位 / 10進位 / 16進位

 

 

 

       

[IIS] 在 Windows Server 上執行 PHP 莫名的慢

原本在Linux非常順暢的Wordpress移植到了Windows Server上卻發生一個頁面要Loading一秒以上,餵狗了一下找了幾種方法來優化一下。

  1. 修改php.ini
    output_buffering修改為Off

    output_buffering = Off
  2. 將php內用到localhost的通通修改為127.0.0.1
  3. 關閉Router的防DDOS功能 <-- 這個功能害我測了好久

修改完後有快一點點了,但還是比不上Linux的速度,可能這就是Windows Server先天上的吃資源吧。

 

 

來源:https://forums.iis.net/t/1153459.aspx?PHP+very+slow+on+IIS7