博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode题解(二)
阅读量:6294 次
发布时间:2019-06-22

本文共 11195 字,大约阅读时间需要 37 分钟。

LeetCode题解(二)

Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

int romanToInt(char* s) {    int len = strlen(s);    int prev = 0;    int result = 0;    int ele = 0;    for (int i = len - 1; i > -1; --i) {        switch (*(s + i))   {            case 'i': case 'I': ele = 1; break;            case 'v': case 'V': ele = 5; break;            case 'x': case 'X': ele = 10; break;            case 'l': case 'L': ele = 50; break;            case 'c': case 'C': ele = 100; break;            case 'd': case 'D': ele = 500; break;            case 'm': case 'M': ele = 1000; break;        }        if (ele < prev) {            result -= ele;        }        else            result += ele;        prev = ele;    }    return result;}

Valid Parentheses

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

bool isValid(char* s) {     int len = (s == NULL) ? 0 : strlen(s);    if (len < 2 || *s == ')' || *s == ']' || *s == '}')        return false;    char s_copy[len];    strcpy(s_copy, s);    char ele;    int left_count = 0, right_count = 0;    bool flag = false;    for (int i = 0; i < len; ++i) {        if (*(s + i) == ')') {            flag = true; ele = '('; ++left_count; s_copy[i] = '\0';        } else if (*(s + i) == ']') {            flag = true; ele = '['; ++left_count; s_copy[i] = '\0';        } else if (*(s + i) == '}') {            flag = true; ele = '{'; ++left_count; s_copy[i] = '\0';        } else {            flag = false; ++right_count;        }        if (flag) {            for (int j = i - 1; j > -1; --j) {                if (s_copy[j] == '\0') {                    if (j == 0)                        return false;                    else                        continue;                } else {                    if (s_copy[j] != ele)                        return false;                    else                        s_copy[j] = '\0';                    break;                }            }        }    }    if (left_count != right_count)        return false;    else        return true;}

Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {    if (l1 == NULL)        return l2;    if (l2 == NULL)        return l1;    struct ListNode* result = NULL;    if (l1->val < l2->val) {        result = l1;        result->next = mergeTwoLists(l1->next, l2);    } else {        result = l2;        result->next = mergeTwoLists(l1, l2->next);    }    return result;}

Valid Sudoku

Determine if a Sudoku is valid, according to: .

1. Each row must have the numbers 1-9 occuring just once.
2. Each column must have the numbers 1-9 occuring just once.
3. And the numbers 1-9 must occur just once in each of the 9 sub-boxes of the grid.

The Sudoku board could be partially filled, where empty cells are filled with the character ‘.’.

A partially filled sudoku which is valid.

Note:

A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

bool isValidSudoku(char** board, int boardRowSize, int boardColSize) {    if (board == NULL || boardRowSize % 3 != 0 || boardColSize % 3 != 0)        return false;    char row_valid[10];    char col_valid[10];    char subboard_valid[10];    for (int i = 0; i < boardRowSize; ++i) {        memset(row_valid, 0, sizeof(char) * 10);        for (int j = 0; j < boardColSize; ++j) {            if (*(*(board + i) + j) != '.') {                if (row_valid[*(*(board + i) +j) - '0'])                    return false;                else                    row_valid[*(*(board + i) + j) - '0'] = 1;            }        }    }    for (int j = 0; j < boardColSize; ++j) {        memset(col_valid, 0, sizeof(char) * 10);        for (int i = 0; i < boardRowSize; ++i) {            if (*(*(board + i) + j) != '.') {                if (col_valid[*(*(board + i) + j) - '0'])                    return false;                else                    col_valid[*(*(board + i) + j) - '0'] = 1;            }        }    }    int n = (boardRowSize / 3) * (boardColSize / 3);    int row = 0;    int col = 0;    for (int i = 0; i < n; ++i) {        memset(subboard_valid, 0, sizeof(char) * 10);        for (int j = 0; j < 9; ++j) {            row = 3 * (i / 3) + j / 3;            col = 3 * (i % 3) + j % 3;            if (*(*(board + row) + col) != '.') {                if (subboard_valid[*(*(board + row) + col) - '0'])                    return false;                else                    subboard_valid[*(*(board + row) + col) - '0'] = 1;            }        }    }    return true;}

Count and Say

The count-and-say sequence is the sequence of integers beginning as follows:

1, 11, 21, 1211, 111221, …

1 is read off as “one 1” or 11.

11 is read off as “two 1s” or 21.
21 is read off as “one 2, then one 1” or 1211.
Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.

/** * 请用户释放返回的指针指向的内存 * */char* countAndSay(int n) {    int N = n > 1 ? expl(n / 4) * 10 : 2;    char* result = (char*)malloc(sizeof(char) * N);     memset(result, 0, sizeof(char) * N);    if (n < 1)        return result;    char* cache = (char*)malloc(sizeof(char) * N);    result[0] = '1';    if (n == 1)        return result;    int count;    char ele;    for (int i = 2; i < n + 1; ++i) {        memset(cache, 0, sizeof(char) * N);        count = 0;        ele = result[0];        for (int j = 0; j < strlen(result); ++j) {            if (result[j] == ele) {                ++count;            } else {                cache[strlen(cache)] = '0' + count;                cache[strlen(cache)] = ele;                ele = result[j];                count = 1;            }            if (j == strlen(result) - 1) {                cache[strlen(cache)] = '0' + count;                cache[strlen(cache)] = ele;            }        }        memcpy(result, cache, sizeof(char) * N);    }    free(cache);    return result;}

Length of Last Word

Given a string s consists of upper/lower-case alphabets and empty space characters ’ ‘, return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

For example,

Given s = “Hello World”,
return 5.

int lengthOfLastWord(char* s) {    if (s == NULL || *s == '\0')        return 0;    int len = strlen(s);    char copy[len + 1];    strcpy(copy, s);    s = ©[0];    char* last_space = strrchr(s, ' ');    // 去首尾空格    while (*s == ' ') {        s += 1;    }    while (last_space == s + strlen(s) - 1) {        *last_space = '\0';        last_space = strrchr(s, ' ');    }    len = strlen(s);    if (len == 0) {        return 0;    }    else {        if (!last_space)            return len;        else            return s + len - 1 - last_space;    }}

Plus One

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

/** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */int* plusOne(int* digits, int digitsSize, int* returnSize) {    int* result = NULL;    bool is_carry = false;    if (digitsSize < 1) {        *returnSize = 0;        return NULL;    }    for (int idx = 0; idx < digitsSize; ++idx) {        if (*(digits + idx) != 9) {            is_carry = false;            break;        } else {            is_carry = true;        }    }    if (is_carry) {        result = (int*)malloc(sizeof(int) * (digitsSize + 1));        *returnSize = digitsSize + 1;        result += 1;    } else {        result = (int*)malloc(sizeof(int) * digitsSize);        *returnSize = digitsSize;    }    int carry_bit = 0;    *(result + digitsSize - 1) = (*(digits + digitsSize - 1) + 1) % 10;    carry_bit = (*(digits + digitsSize - 1) + 1) / 10;    for (int index = digitsSize - 2; index > -1; --index) {        *(result + index) = (*(digits + index) + carry_bit) % 10;        carry_bit = (*(digits + index) + carry_bit) / 10;    }    if (is_carry) {        result -= 1;        *result = carry_bit;    }    return result;}

Add Binary

Given two binary strings, return their sum (also a binary string).

For example,

a = “11”
b = “1”
Return “100”.

char* addBinary(char* a, char* b) {    if (a == NULL)        return b;    if (b == NULL)        return a;    int len_a = strlen(a);    int len_b = strlen(b);    if (len_a < len_b)        return addBinary(b, a);    int diff = len_a - len_b;    b -= diff;    int carry_bit = 0;    char tmp[len_a + 2];    char* result;    memset(tmp, 0, sizeof(char)* (len_a + 2));    result = tmp;    int sum = 0;    for (int idx = len_a - 1; idx > diff - 1; --idx) {        sum = (a[idx] - '0') + (b[idx] - '0') + carry_bit;        if (sum == 0) {            *result = '0'; carry_bit = 0;        } else if (sum == 1) {            *result = '1'; carry_bit = 0;        } else if (sum == 2) {            *result = '0'; carry_bit = 1;        } else if (sum == 3) {            *result = '1'; carry_bit = 1;        }        ++result;    }    for (int idx = diff - 1; idx > -1; --idx) {        sum = (a[idx] - '0') + carry_bit;        if (sum == 0) {            *result = '0'; carry_bit = 0;        } else if (sum == 1) {            *result = '1'; carry_bit = 0;        } else if (sum == 2) {            *result = '0'; carry_bit = 1;        }        ++result;    }    if (carry_bit)        *result = '1';    diff = strlen(tmp);    result = (char*)calloc(diff + 1, sizeof(char));    for (int idx = diff - 1; idx > -1; --idx)        *(result + idx) = tmp[diff - idx - 1];    return result;}

Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

int climbStairs(int n) {    if (n < 3)        return n;    int fibo[n];    fibo[0] = 1;    fibo[1] = 2;    for (int i = 2; i < n; ++i) {        fibo[i] = fibo[i - 1] + fibo[i - 2];    }    return fibo[n - 1];}

Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,

Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* deleteDuplicates(struct ListNode* head) {    if (head == NULL || head->next == NULL)        return head;    struct ListNode* result = head;    while (head && head->next) {        if (head->val == head->next->val) {            head->next = head->next->next;        } else {            head = head->next;        }    }    return result;}

转载于:https://www.cnblogs.com/corfox/p/6063311.html

你可能感兴趣的文章
如何清理mac系统垃圾
查看>>
企业中最佳虚拟机软件应用程序—Parallels Deskto
查看>>
Nginx配置文件详细说明
查看>>
怎么用Navicat Premium图标编辑器创建表
查看>>
Spring配置文件(2)配置方式
查看>>
MariaDB/Mysql 批量插入 批量更新
查看>>
ItelliJ IDEA开发工具使用—创建一个web项目
查看>>
solr-4.10.4部署到tomcat6
查看>>
切片键(Shard Keys)
查看>>
淘宝API-类目
查看>>
virtualbox 笔记
查看>>
Git 常用命令
查看>>
驰骋工作流引擎三种项目集成开发模式
查看>>
SUSE11修改主机名方法
查看>>
jdk6.0 + Tomcat6.0的简单jsp,Servlet,javabean的调试
查看>>
Android:apk签名
查看>>
2(2).选择排序_冒泡(双向循环链表)
查看>>
MySQL 索引 BST树、B树、B+树、B*树
查看>>
微信支付
查看>>
CodeBlocks中的OpenGL
查看>>