LeetCode Beginner Algorithm Exercise - String

344. Reverse  String

Please write a function whose function is to reverse the input string.

Example:

Input: s = "hello"
 Return: "olleh"
class Solution:
    def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        #[start:end:step]step default=1
        return s[::-1]
7. Reverse Integers 

Given a 32-bit signed integer, invert the numbers in the integer.

Example 1:

Input: 123
 Output: 321

 Example 2:

Input: -123
 Output: -321

Example 3:

Input: 120
 Output: 21

Notice:

Suppose that our environment can only store 32-bit signed integers in the range [−2 31 , 2 31  − 1]. According to this assumption, if the inverted integer overflows, 0 is returned.

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """                       
        if x < 0:
            r = int(str(x*-1)[::-1]) * -1
        elif x < 10:
            return x
        else:
            r = int(str(x)[::-1])
        if r > 2**31 - 1 or r < -2**31:
            r = 0
        return r

387. The  first unique character in a string

Given a string, find its first unique character and return its index. Returns -1 if not present.

Case:

s = "leetcode"
returns 0.

s = "loveleetcode",
Return to 2.

 

Note: You can assume that the string contains only lowercase letters.


class Solution:
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        from collections import Counter
        c1 = Counter(s)
        a = list()
        for i in c1.keys():
            if c1[i] == 1:
                a.append(s.index(i))
        if len(a) == 0:
            return -1
        else :
            return min(a)
class Solution:
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        #When the index list is empty, it returns -1, if it is not empty, it returns the minimum value of the index list
        import string  
        return min([s.index(ch) for ch in string.ascii_lowercase if s.count(ch) == 1] or [-1])



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325980765&siteId=291194637