Leetcode 题目整理-4 Longest Common Prefix & Remove Nth Node From End of List
2024-09-01 21:35:41
14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
注:这题竟然连个示例都没有,说明特殊情况并不多,就是要找出所有字符串的最长公共前缀。他应该不会超过所有字符串中最短的那个,可以试着找出最短长度n,然后每个都读取和比较n个,并根据情况不断减小那个n.\
if (strs.size() == )
{
return "";
}
int n{int(strs.front().size())};
if (n == )
{
return "";
}
for (vector<string>::iterator str_i = strs.begin()+; str_i != strs.end(); str_i++)
{
if ((*str_i).size() < n)
{
n = (*str_i).size();
}
int temp{n};//感觉有点儿多余
for (int i = ; i < n; i++)
{
if ((*str_i).at(i) != (*(str_i - )).at(i))
{
temp = i;
break;
}
}
n = temp;
} string longest_prefix(strs.front(),,n);
return longest_prefix;
19. Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and return its head.
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.
Note:
Given n will always be valid.
Try to do this in one pass.
注:给出一个链表,把倒数第n个元素移除。听起来很常用的技术,了解一下链表的结构,用处 ,优势,再来做这个题。
今天关于链表的部分没有完成,明天继续
int i{ };
ListNode *temp,*fronter ,*backer,*curNode;
temp = head;
//fronter从第一个节点开始向后移动,直到第n个,或者到了结尾
for (fronter = temp; i < n && !(fronter->next==NULL); fronter = fronter->next,i++);//(*fronter).next)
if (fronter->next == NULL)//如果是因为到了结尾而结束的循环,那么说明要删除的点在head
{
ListNode *tmp = head;
if (head->next==NULL)//整个链表只有一个节点
head= ;
else
head = head->next;
return head;
}
//如果是因为fornter已经过去n个了,那么这个时候给backer赋值
curNode = head;
//二者同时继续向后遍历,直到fronter走到结尾时,删除backer之后的那个节点
for (; fronter->next != NULL; fronter = fronter->next){ backer=curNode;
curNode = curNode->next;
}
//删除backer后面的节点
backer->next = curNode->next;
return head;
最新文章
- java 代码解压7z(带密码)转载请注明出处,谢谢
- struts2 配置拦截器
- PyQt4学习资料汇总
- 设计模式学习之组合模式(Composite,结构型模式)(10)
- 130. Surrounded Regions -- 被某字符包围的区域
- 【POJ】【2699】The Maximum Number of Strong Kings
- 打造自己的程序员品牌(摘自Infoq)
- 在Thinkphp3.2 中使用PHPMailer 发送邮件
- 动态更新UI的方式
- IE6、火狐不支持a:visited
- 《算法导论》习题2.3-7 查找集合S中是否有两个元素和为X---Java实现
- 接口测试——Java + TestNG 国家气象局接口(json解析)实例
- 机器学习相关的tutorial
- springboot添加多数据源连接池并配置Mybatis
- Apple IAP Subscriptions
- 2015 HIAST Collegiate Programming Contest H
- rx.js 的冷和热观察
- mysql中的 随机字符串的生成
- group replication &;&; Galera replication
- POJ3241 Object Clustering(最小生成树)题解