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() == 0) { return ""; } int n{int(strs.front().size())}; if (n == 0) { return ""; } for (vector<string>::iterator str_i = strs.begin()+1; str_i != strs.end(); str_i++) { if ((*str_i).size() < n) { n = (*str_i).size(); } int temp{n};//感觉有点儿多余 for (int i = 0; i < n; i++) { if ((*str_i).at(i) != (*(str_i - 1)).at(i)) { temp = i; break; } } n = temp; } string longest_prefix(strs.front(),0,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{ 1 }; 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= 0; 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;