python_lintcode_166链表倒数第n个节点_671循环单词

来源:互联网 发布:淘宝司法拍卖车靠谱吗 编辑:程序博客网 时间:2024/06/06 19:06

166链表倒数第n个节点

题目

http://www.lintcode.com/zh-cn/problem/nth-to-last-node-in-list/

找到单链表倒数第n个节点,保证链表中节点的最少数量为n。

Example
给出链表 3->2->1->5->null和n = 2,返回倒数第二个节点的值1.

思路

-逆向:从头到倒数第n个数,求得该值

代码

"""Definition of ListNodeclass ListNode(object):    def __init__(self, val, next=None):        self.val = val        self.next = next"""class Solution:    """    @param head: The first node of linked list.    @param n: An integer.    @return: Nth to last node of a singly linked list.     """    def nthToLast(self, head, n):        # write your code here        current=head         count=0        #计算链表的节点数        while current!=None:            count+=1            current=current.next        x=head        #得到第count-n-1=倒数第n个节点        for i in range(count-n):            x=x.next        return x

671循环单词

题目

http://www.lintcode.com/zh-cn/problem/rotate-words/

The words are same rotate words if rotate the word to the right by loop, and get another. Count how many different rotate word sets in dictionary.

E.g. picture and turepic are same rotate words.

Notice

所有单词均为小写。

Have you met this question in a real interview? Yes
Example
Given dict = [“picture”, “turepic”, “icturep”, “word”, “ordw”, “lint”]
return 3.

“picture”, “turepic”, “icturep” are same ratote words.
“word”, “ordw” are same too.
“lint” is the third word that different from the previous two words.

思路

  • 数据不是按着循环单词的顺序,即可能最后一个单词是第一个的循环单词,因此,需要将之前的循环单词保存
  • 本代码思路很简单,就是将words的单词与x(所有出现的循环单词)进行比对,若单词在x,则计数器count+=1,否则,将该单词的所以可能出现的循环单词存放在x

代码

class Solution:    """    @param: words: A list of words    @return: Return how many different rotate words    """    def countRotateWords(self, words):        # Write your code here        if len(words)<2:return len(words)        x=self.bu(words[0],[])        count=1        #判断是否是之前出现的循环单词        for i in words:           if i in x:continue           else:                count+=1                x=self.bu(i,x)        return count    """    bu()函数:该单词所有的循环结果,由于给出的数据不是按顺序的    所以有可能最后一个是第一个的循环单词    a代表新添加的单词,b为已经存放的循环单词    """    def bu(self,a,b):        m=len(a)        a=a+a        for i in range(m):            b.append(a[i:m+i])        return b