您的位置:首页 > 其它

LeetCode 2015.7.15 27,20,19,14,232,118

2016-02-13 20:30 405 查看
LeetCode 2015.7.15 27,20,19,14,232,118

27 Remove Element
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int len=nums.size();
vector<int> tmp;
tmp.clear();
for(int i=0;i<len;i++)
{
if (nums[i]!=val)
tmp.push_back(nums[i]);
}
nums.clear();
int lentmp=tmp.size();
nums.resize(lentmp);
for(int i=0;i<lentmp;i++)
nums[i]=tmp[i];
return lentmp;

}
};

20 Valid Parentheses
class Solution {
public:
bool isValid(string s) {
stack<int> st;
int flag[300]={0};
flag['[']=1;flag[']']=-1;
flag['{']=2;flag['}']=-2;
flag['(']=3;flag[')']=-3;
while (!st.empty()) st.pop();
st.push(4);
int len=s.size();
for(int i=0;i<len;i++)
{
if (flag[s[i]]>0) st.push(flag[s[i]]);
else
{
if (flag[s[i]]+st.top()==0)
st.pop();
else
return false;
}
}
if (st.size()!=1) return false;else return true;

}
};

19 Remove Nth Node From End of List
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int len=0;
ListNode* tmphead=head;
while (tmphead!=NULL)
{
len++;
tmphead=tmphead->next;
}
int split=len-n;
tmphead=head;
for(int i=1;i<split;i++)
{
tmphead=tmphead->next;
}
if (n==len)
head=head->next;
else
tmphead->next=tmphead->next->next;
return head;

}
};

14 Longest Common Prefix
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int num= strs.size();
if (num==0) return "";
int len=INT_MAX;
for(int i=0;i<num;i++)
{
if (strs[i].size()<len)
len=strs[i].size();
}
if (len==0) return "";
string ans;
bool flag=true;
ans.clear();
for(int i=0;i<len;i++)
{
for(int j=1;j<num;j++)
{
if (strs[j][i]!=strs[j-1][i])
{
flag =false;
break;
}
}
if (!flag) break;
ans=ans+strs[0][i];
}
return ans;
}
};

232 Implement Queue using Stacks
class Queue {
private:
stack<int> s1,s2;
public:
// Push element x to the back of queue.
void push(int x) {
s1.push(x);
}

// Removes the element from in front of queue.
void pop(void) {
if (!s2.empty()) s2.pop();
else
{
while (!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
s2.pop();
}
}

// Get the front element.
int peek(void) {
if (!s2.empty()) return s2.top();
while (!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
return s2.top();
}

// Return whether the queue is empty.
bool empty(void) {
if (s1.empty() && s2.empty()) return true;
return false;

}
Queue(){
while (!s1.empty()) s1.pop();
while (!s2.empty()) s2.pop();
}
};

118 Pascal's Triangle
class Solution {
public:
vector< vector<int> > generate(int numRows) {
vector< vector<int> > ans;
vector<int> line;
ans.clear();
if (numRows==0) return ans;
line.clear();
line.push_back(1);
ans.push_back(line);
if (numRows==1) return ans;
for(int i=1;i<numRows;i++)
{
line.clear();
line.push_back(1);
int len=i-1;
for(int j=0;j<len;j++)
line.push_back(ans[i-1][j]+ans[i-1][j+1]);
line.push_back(1);
ans.push_back(line);
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: