您的位置:首页 > 其它

leetcode随笔VIII

2016-03-12 12:55 169 查看
leetcode题目

1.1题目描述

1.2知识点及思路

1.3代码

总结

一.leetcode题目

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

题目描述:1读成11,11读成21,21读成1211,问第n个数读成什么?

知识点:循环遍历;前变量保存

思路:①从第一个数开始读起②pre[保存前一变量的值③相同则更新累计数值(count),不同则更新为1

代码如下:

class Solution {
public:
string countAndSay(int n)
{
if(n==0)
return NULL;
if(n==1)
return "1";

string temp("11");
for(int i=2;i<n;i++)
{
int count=1;
char pre=temp[0];
stringstream temp2;
for(int j=1;j<temp.size();j++)
{
if(pre==temp[j])
count++;
else
{
temp2<<count<<pre;
pre=temp[j];
count=1;
}
}
temp2<<count<<pre;
temp=temp2.str();
}
return temp;
}
};


2.Longest Common Prefix

题目描述:找出所有字符串的最长公共前缀

知识点:指针;遍历

思路:①求出最短串长②设立总字符串个数(n)个指针③依次对应遍历比较

代码如下:

class Solution {
private:
int mins(vector<string>&strs)
{
int min=0;
for(int i=0;i<strs.size();i++)
min=min>strs[i].size()?min:strs[i].size();
return min;
}
public:
string longestCommonPrefix(vector<string>& strs)
{
string prefix;
bool flag=true;
int min=mins(strs);
for(int j=0;j<min;j++)
{
char temp=strs[0][j];
for(int i=0;i<strs.size();i++)
{
if(temp!=strs[i][j])
flag=false;
}
if(flag)
prefix=prefix+strs[0][j];
else
break;
}
return prefix;
}
};


3.Implement strStr()

题目描述:实现是否为字串的判断

知识点:遍历;kmp

思路:暴力方法->循环比较



kmp方法->

/article/4999833.html

代码如下(暴力):

int strStr(char* haystack, char* needle)
{
int hLength=strlen(haystack);
int nLength=strlen(needle);
if(hLength<nLength)
return -1;
for(int i=0;i<=hLength-nLength;i++)
if(strncmp(haystack+i,needle,nLength)==0)
return i;
return -1;
}


4.Count Primes

题目描述:计算质数的个数

知识点:hashTable

思路:①建立hashTable②分别找出被2,3,5,….整除的数,并做标记③找出未标记的数



代码如下:

class Solution {
private:
/*   bool isPrimes(int n)
{
if(n<=1)
return false;
for(int i=2;i*i<=n;i++)
if(n%i==0)
return false;
return true;
}
public:
int countPrimes(int n)
{
int  count=0;
for(int i=1;i<n;i++)
if(isPrimes(i))
count++;
return count;
}*/
public:
void Eratosthenes(vector<bool>&num,int n)
{
num[0]=false;
for(int i=2;pow(i,2)<=n;i++)
{
if (num[i - 1])
for(int j=pow(i,2);j<n;j+=i)
num[j-1]=false;
}
}
int countPrimes(int n)
{
if(n==0)
return 0;
vector<bool> num(n-1,true);
Eratosthenes(num,n);
int count=0;
for(int i=0;i<num.size();i++)
if(num[i])
count++;
return count;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: