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

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 ListNode
class 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值