LeetCode的easy题集合(C++实现)四

来源:互联网 发布:运营商网络制式 编辑:程序博客网 时间:2024/06/05 09:03

1.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.

ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {        if(l1==NULL&&l2==NULL)        return NULL;        else if(l1==NULL)        return l2;        else if(l2==NULL)        return l1;        ListNode *helper=new ListNode(0);        ListNode *head=helper;        while(l1 && l2)        {             if(l1->val<l2->val) helper->next=l1,l1=l1->next;             else helper->next=l2,l2=l2->next;             helper=helper->next;        }        if(l1) helper->next=l1;        if(l2) helper->next=l2;        return head->next;    }

2.Valid Parentheses
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid. 这是一个标准的进栈出栈问题。

bool isValid(string s) {        vector<char> mid;    int len = s.length();    int i = 0;    while (i<len)    {        while ((s[i] == '(' || s[i] == '{' || s[i] == '[') && i<len)        {            mid.push_back(s[i]);            i++;        }        if (s[i] == ')')        {            if (i<1 || mid.back() != '(')                return false;            else            {                mid.pop_back();            }        }        else if (s[i] == ']')        {            if (i<1 || mid.back() != '[')                return false;            else            {                mid.pop_back();            }        }        else if (s[i] == '}')        {            if (i<1 || mid.back() != '{')                return false;            else            {                mid.pop_back();            }        }        i++;    }    if (i >= len&&mid.size() == 0)        return true;    else        return false;    }

3.Remove Nth Node From End of List .
For example,Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.

ListNode *removeNthFromEnd(ListNode *head, int n) {        ListNode* result=head;        ListNode* start=head;        int i=0;        while(head->next!=NULL)        {            i++;            head=head->next;        }        if(i==0)        return NULL;        int num=i-n;        if(num==-1)        {            result=start->next;            delete start;            return result;        }        while(num>0)        {            start=start->next;            num--;        }        ListNode* mid=start;        mid=mid->next;        if(n==1)        {          start->next=NULL;          delete mid;          }        else        {         start->next=mid->next;         delete mid;        }        return result;    }

4.Longest Common Prefix
找到一组字符串中最长的公共前缀。

string longestCommonPrefix(vector<string>& strs) {        string res="";        int k=0,len=strs.size();        if(len==0)        return res;        int minlen=strs[0].length();        for(int j=1;j<len;j++) //最短的字符串长度        {            if(minlen>strs[j].length())               minlen=strs[j].length();        }        while(k<minlen)        {            int i=0;            for(;i<len-1;i++)            {                if(strs.at(i)[k]!=strs.at(i+1)[k])                  break;            }            if(i<len-1)              return res;            else            {              res+=strs.at(0)[k];              k++;            }        }        return res;    }

5.Roman to Integer
将罗马数字变为整数。罗马数字规则,当左边的数比右边小时要用右边的数减左边的数。如IV为4.

int getRomanValue(char c) {          switch(c) {              case 'I': return 1;               case 'V': return 5;              case 'X': return 10;             case 'L': return 50;              case 'C': return 100;              case 'D': return 500;              case 'M': return 1000;              default: return 0;          }      }      int romanToInt(string s) {        int length=s.size();        if(length<1) return 0;        int sub=getRomanValue(s[0]);        int last=sub;        int cur,sum=0;        for(int i=1;i<length;i++)        {            cur=getRomanValue(s[i]);            if(cur==last)            {              sub+=cur;            }            else if(cur<last)            {                sum+=sub;                sub=cur;            }            else            {                sub=cur-sub;            }            last=cur;        }        sum+=sub;        return sum;    }

6.Palindrome Number
判断一个数是否为回文数。4321234为一个回文数。

 bool isPalindrome(int x) {        if(x<0)        return false;        if(x==0)        return true;        int base=1;        while(x/base>=10)  //用于求x的最高位的数          base*=10;        int high=0,low=0;        while(x)        {            high=x/base;            low=x%10;            if(high!=low)            return false;            x-=high*base;            x/=10;            base/=100;        }        return true;    }

7.String to Integer
将字符串转为整型,关键问题是防止溢出。

int atoi(string str) {        int length=str.size();        if(length==0)        return 0;        int sum=0,flag=1;        int i=0,count=0;        while(str[i]==' ')//去掉前面空格        {            i++;        }        if(str[i]=='+')        {            i++;        }        else if(str[i]=='-')//标记为负数        {            flag=-1;            i++;        }        while(str[i]=='0')//去掉前面为0的数        {            i++;        }        int start=i;        for(;i<length;i++)        {            str[i]=str[i]-'0';            if(str[i]>=0&&str[i]<=9)            {                sum=sum*10+str[i];                count++;                if(count>10||(count==10&&(sum<0||str[start]>2))) //溢出                  return flag<0?INT_MIN:INT_MAX;             }            else               return (int)sum*flag;        }        return (int)sum*flag;    }

8.Reverse Integer
同上个问题一样,主要是防止溢出。

int reverse(int x) {    bool flag = false;    long long sum = 0; //输入为int ,long long 类型可以防止溢出,    if(x==INT_MIN)      return 0;    if (x<0)    {        flag = true;        x = -x;    }    while (x)    {        sum = 10 * sum + x % 10;        x /= 10;    }    if (sum >= INT_MAX)    {        return 0;    }    else if (flag == true)    {        sum = -int(sum);        return sum;    }    else        return (int)sum;    }

9.ZigZag Conversion
The string “PAYPALISHIRING” is written in a zigzag pattern
P A H N
A P L S I I G
Y I R
And then read line by line: “PAHNAPLSIIGYIR”
nRows表示行,num表示字符串的序列号,可以看出第一行与最后一行满足num+=2nRows2,中间的奇数行满足num+=2(nRowsi1),偶数行满足num+=2i

 string convert(string s, int nRows) {        int len=s.length();        if(len<nRows||nRows==1||len==0)        return s;        bool flag=true;        string res="";        for(int i=0;i<nRows;i++)        {            int num=i;            res+=s[num];            for(int k=1;num<len;k++)            {                if(i==0||i==nRows-1)                {                    num+=2*nRows-2;                }                else                {                    if(k& 0x1)                      num+=2*(nRows-i-1);                    else                      num+=2*i;                }                if(num<len)                res+=s[num];            }        }        return res;    }
0 0
原创粉丝点击