[力扣] 算法 59 (C#)

59. 螺旋矩阵 II

public class Solution {
    public int[][] GenerateMatrix(int n) {
        var ret = new int[n][];
        for (var i = 0; i < ret.Length; i++)
            ret[i] = new int[n];
        var loc = (x:0, y:0);
        var dir = (x:0, y:1);
        for(var i = 0; i < n * n; i++)
        {
            ret[loc.x][loc.y] = i + 1;
            var next = (x:loc.x + dir.x, y:loc.y + dir.y);
            if(next.x < 0 || next.y<0||next.x == n || next.y == n || ret[next.x][next.y] != 0)
            {
                dir = (dir.y, -dir.x);
                next = (x: loc.x + dir.x, y: loc.y + dir.y);
            }
            loc = next;
        }
        return ret;
    }
}

[力扣] 算法 227 (C#)

227. 基本计算器 II

直接拿 224 的代码改(尽管这道题不用处理括号)

public class Solution
{
    public int Calculate(string s) => Bar(Foo(s));

    List<IConvertible> Foo(string s)
    {
        var stack = new Stack<char>(s.Length);// ( + - * / only
        var ret = new List<IConvertible>(s.Length);
        for (var i = 0; i < s.Length; i++)
        {
            var ch = s[i];
            switch (ch)
            {
                case '(':
                    stack.Push('(');
                    break;
                case ')':
                    char top;
                    while ((top = stack.Pop()) != '(')
                        ret.Add(top);
                    break;
                case '+':
                case '-':
                    while (stack.Count > 0 && stack.Peek() != '(')
                        ret.Add(stack.Pop());
                    stack.Push(ch);
                    break;
                case '*':
                case '/':
                    while (stack.Count > 0 && (stack.Peek() == '*' || stack.Peek() == '/'))
                        ret.Add(stack.Pop());
                    stack.Push(ch);
                    break;
                case ' ':
                    break;
                default:// 0 ~ 9
                    long num = ch - '0';
                    for (; i + 1 < s.Length && s[i + 1] >= '0' && s[i + 1] <= '9'; i++)
                    {
                        num *= 10;
                        num += s[i + 1] - '0';
                    }
                    ret.Add(num);
                    break;
            }
        }
        while (stack.Count > 0)
            ret.Add(stack.Pop());
        return ret;
    }

    int Bar(List<IConvertible> foo)
    {
        var stack = new Stack<long>();
        foreach (var f in foo)
        {
            switch (f)
            {
                case '+':
                    stack.Push(stack.Pop() + stack.Pop());
                    break;
                case '-':
                    if (stack.Count > 1)
                        stack.Push(-(stack.Pop() - stack.Pop()));
                    else
                        stack.Push(-stack.Pop());
                    break;
                case '*':
                    stack.Push(stack.Pop() * stack.Pop());
                    break;
                case '/':
                    var got = stack.Pop();
                    stack.Push(stack.Pop() / got);
                    break;
                default:// long
                    stack.Push((long)f);
                    break;
            }
        }
        return (int)stack.Peek();
    }
}

[力扣] 算法 224 (C#)

224. 基本计算器

public class Solution
{
    public int Calculate(string s) => Bar(Foo(s));

    List<IConvertible> Foo(string s)
    {
        var stack = new Stack<char>(s.Length);// ( + - only
        var ret = new List<IConvertible>(s.Length);
        for (var i = 0; i < s.Length; i++)
        {
            var ch = s[i];
            switch (ch)
            {
                case '(':
                    stack.Push('(');
                    break;
                case ')':
                    char top;
                    while ((top = stack.Pop()) != '(')
                        ret.Add(top);
                    break;
                case '+':
                case '-':
                    while (stack.Count > 0 && stack.Peek() != '(')
                        ret.Add(stack.Pop());
                    stack.Push(ch);
                    break;
                case ' ':
                    break;
                default:// 0 ~ 9
                    long num = ch - '0';
                    for (; i + 1 < s.Length && s[i + 1] >= '0' && s[i + 1] <= '9'; i++)
                    {
                        num *= 10;
                        num += s[i + 1] - '0';
                    }
                    ret.Add(num);
                    break;
            }
        }
        while (stack.Count > 0)
            ret.Add(stack.Pop());
        return ret;
    }

    int Bar(List<IConvertible> foo)
    {
        var stack = new Stack<long>();
        foreach (var f in foo)
        {
            switch (f)
            {
                case '+':
                    stack.Push(stack.Pop() + stack.Pop());
                    break;
                case '-':
                    if (stack.Count > 1)
                        stack.Push(-(stack.Pop() - stack.Pop()));
                    else
                        stack.Push(-stack.Pop());
                    break;
                default:// long
                    stack.Push((long)f);
                    break;
            }
        }
        return (int)stack.Peek();
    }
}

参考资料

[力扣] 算法 263 (C#)

263. 丑数

Plan A

public class Solution
{
    public bool IsUgly(int n)
    {
        if (n == 0)
            return false;
        if (n == 1)
            return true;
        if ((n % 2) == 0)
            return IsUgly(n / 2);
        if ((n % 3) == 0)
            return IsUgly(n / 3);
        if ((n % 5) == 0)
            return IsUgly(n / 5);
        return false;
    }
}

Plan B,易扩展

public class Solution
{
    public bool IsUgly(int n)
    {
        if (n == 0)// 这道题也可以判断 n < 1
            return false;
        Bar(ref n, 2, 3, 5);
        return n == 1;
    }

    void Foo(ref int n, int a)
    {
        while ((n % a) == 0)
            n /= a;
    }

    void Bar(ref int n, params int[] @as)
    {
        foreach (var a in @as)
            Foo(ref n, a);
    }
}

[力扣] 算法 1047 (C#)

1047. 删除字符串中的所有相邻重复项

Plan A (这会超时是我万万没有想到的)

public class Solution
{
    public string RemoveDuplicates(string S)
    {
        var deque = new LinkedList<char>();
        foreach(var ch in S)
        {
            if(deque.Count > 0)
            {
                if (deque.Last() == ch) { 
                    deque.RemoveLast();
                    continue;
                }
            }
            deque.AddLast(ch);
        }
        return string.Concat(deque);
    }
}

Plan B

public class Solution
{
    public string RemoveDuplicates(string S)
    {
        var chs = new char[S.Length];
        var leng = 0;
        foreach(var ch in S)
        {
            if (leng > 0 && chs[leng - 1] == ch)
                leng--;
            else
                chs[leng++] = ch;
        }
        return new string(chs, 0, leng);
    }
}

[力扣] 算法 132 (C#)

132. 分割回文串 II

public class Solution
{
    public int MinCut(string s)
    {
        if (s.Length == 0)
            return 0;
        var part = new bool[s.Length, s.Length];
        part[0, 0] = true;
        for (var i = 1; i < s.Length; i++)
            part[i, i] = part[i, i - 1] = true;
        for (var i = 1; i < s.Length; i++)
            for (var j = 0; j < s.Length - i; j++)
                part[j, i + j] = part[j + 1, i + j - 1] && s[j] == s[i + j];

        // 这一段原本我是用131的的Foo()改的,结果超时了。按官方的解法写了如下代码
        var f = new int[s.Length];
        Array.Fill(f, s.Length);
        for (var i = 0; i < s.Length; i++)
            if (part[0, i])
                f[i] = 0;
            else
                for (var j = 0; j < i; j++)
                    if (part[j + 1, i])
                        f[i] = Math.Min(f[i], f[j] + 1);
        return f[^1];
    }
}

[力扣] 算法 131 (C#)

131. 分割回文串

public class Solution
{
    public IList<IList<string>> Partition(string s)
    {
        if (s.Length == 0)
            return new List<IList<string>>();
        var part = new bool[s.Length, s.Length];
        part[0, 0] = true;
        for (var i = 1; i < s.Length; i++)
            part[i, i] = part[i, i - 1] = true;
        for (var i = 1; i < s.Length; i++)
            for (var j = 0; j < s.Length - i; j++)
                part[j, i + j] = part[j + 1, i + j - 1] && s[j] == s[i + j];
        var ret = new List<IList<string>>();
        var temp = new List<string>(s.Length);
        Foo(ret, temp, 0, part, s);
        return ret;
    }

    void Foo(List<IList<string>> ret, IList<string> temp, int index, bool[,] part, string s)
    {
        if (index == s.Length)
        {
            ret.Add(new List<string>(temp));
        }
        else
        {
            for (var i = index; i < s.Length; i++)
            {
                if (!part[index, i])
                    continue;
                temp.Add(s[index..(i + 1)]);
                Foo(ret, temp, i + 1, part, s);
                temp.RemoveAt(temp.Count - 1);
            }
        }
    }
}

[力扣] 算法 503 (C#)

503. 下一个更大元素 II

public class Solution {
    const int NON_EXIST = -1;
    public int[] NextGreaterElements(int[] nums)
    {
        if (nums?.Length == 0)
            return Array.Empty<int>();
        if (nums.Length == 1)
            return new int[] { NON_EXIST };
        var ret = new int[nums.Length];
        Array.Fill(ret, NON_EXIST);
        for (var i = ret.Length - 2; i >= 0; i--)
        {
            if (nums[i] < nums[i + 1])
            {
                ret[i] = i + 1;
            }
            else
            {
                var curr = i + 1;
                while (ret[curr] != NON_EXIST)
                {
                    curr = ret[curr];
                    if (nums[i] < nums[curr])
                    {
                        ret[i] = curr;
                        break;
                    }
                }
            }
        }
        for(var i = ret.Length - 1; i >= 0; i--)
        {
            if (ret[i] != NON_EXIST)
                continue;
            var next = (i + 1) % ret.Length;
            while (next != NON_EXIST)
            {
                if(nums[i] < nums[next])
                {
                    ret[i] = next;
                    break;
                }
                next = ret[next];
            }
        }
        for (var i = 0; i < ret.Length; i++)
            if (ret[i] != NON_EXIST)
                ret[i] = nums[ret[i]];
        return ret;
    }
}

// 没想到用单调栈

[力扣] 算法 1296 (C#)

1296. 划分数组为连续数字的集合

public class Solution
{
    public bool IsPossibleDivide(int[] nums, int k)
    {
        if (k > 1)
        {
            var map = new SortedDictionary<int, int>();
            foreach (var num in nums)
                if (map.ContainsKey(num))
                    map[num]++;
                else
                    map[num] = 1;
            while(map.Count > 0)
            {
                var (key,value) = map.First();
                for(var i = 0; i < k; i++)
                {
                    if (!map.ContainsKey(key + i) || (map[key + i] -= value) < 0)
                        return false;
                    if (map[key + i] == 0)
                        map.Remove(key + i);
                }
            }
        }
        return true;
    }
}