(1) Longest Substring Without Repeating Characters
此题用一个hash table保存每个字符上一次出现过的位置。从前往后扫描,假如发现字符上次出现过,就把当前子串的起始位置start移动到上次出现过的位置之后——这是为了保证从start到i的当前子串中没有任何重复字符。同时,由于start移动,当前子串的内容改变,start移动过程中经历的字符都要剔除。[1]
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int begin=0;
int maxlen=0;
int hashtable[256];
memset(hashtable,-1,256*sizeof(int));
for(int i=0;i<s.size();i++)
{
if(hashtable[s[i]]!=-1)
while(begin<=hashtable[s[i]])
{
hashtable[s[begin]]=-1;
begin++;
}
maxlen=max(maxlen,i-begin+1);
hashtable[s[i]]=i;
}
return maxlen;
}
};
(2) Rotate List
游标指针从头节点向后移动,当指向尾节点时,得到链表长度len,同时将链表头尾相连,接着游标再向后移动 k % len 步得到结果链表的尾节点。[2]
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if(!head)
return head;
int len=1;
ListNode *cur=head,*ret;
while(cur->next)
{
cur=cur->next;
len++;
}
cur->next=head;
len=len-k%len;
while(len>0)
{
cur=cur->next;
len--;
}
ret=cur->next;
cur->next=NULL;
return ret;
}
};
参考:
[1] http://blog.csdn.net/cshaxu/article/details/12433931
[2] http://www.cnblogs.com/infinityu/archive/2013/05/14/3077364.html