Algorithm Exercise--String Related

word inversion

Reverse all words in a string.
1. There are only 26 uppercase or lowercase English letters that constitute a word;
2. Characters that do not constitute a word are regarded as word separators;
3. The word separator after inversion is required to be represented by a space; if the original string contains When there are multiple separators between adjacent words, only one space separator is allowed after inverted conversion;
4. Each word can have a maximum of 20 letters;

Enter description:
Enter a line of string

Output description:
Output the inverted result of the word

Example 1
Input:
I am a student
Output:
student a am I

Example 2
Input:
$bo*y gi!r#lOutput
:
lr gi y bo

python implementation, the key is to find all the words

while True:
    try:
        s = input()

        # 找出所有的单词
        word = ""
        words = []
        for i in s:
            if i.isalpha():
                word += i
            else:
                if word:
                    words.append(word)
                    word = ""
        
        if word:
            words.append(word)
        result = " ".join(words[::-1])

        print(result)

    except:
        break

 

Calculate the length of the last word of a string

pending
 

Count the number of occurrences of a character

Write a program that accepts a string consisting of letters, numbers, and spaces, and a character, and then outputs the number of occurrences of that character in the string. (uppercase and lowercase letters are not distinguished)

Input description:
Enter a string consisting of letters, numbers, and spaces in the first line, and
enter a character (non-space) in the second line.

Output description:
The number of characters contained in the output string. (uppercase and lowercase letters are not distinguished)

Example 1
Input:
ABCabc
A
Output:
2
python implementation

def statistic_char_num():
    s1 = input()
    s2 = input().strip().lower()

    num = 0
    for i in s1.lower():
        if i == s2:
            num += 1

    print(num)

statistic_char_num()

 

Obvious random numbers

Generate N random integers between 1 and 500.
Delete the duplicate numbers, that is, keep only one identical number, then sort these numbers from small to large, and output them in the sorted order.

1≤N≤1000
1≤val≤500

Input description:
In the first line, enter the number N of random integers; in the next N lines, enter an integer in each line;
it represents the randomly generated number.
Output description:
Output multiple lines, indicating the processed results

Example 1
input:
3
2
2
1

Output:
1
2

Description:
Input explanation:
The first number is 3, that is, N=3 in this small example, which means that the computer generated 3 random integers between 1 and 500, and then each line has a random number, a total of 3 lines. , that is, these three random numbers are:
2
2
1
, so the output of the sample is:
1
2

pending…

palindrome string

  1. Determine whether a string is a palindrome string.
  2. Find the largest palindrome substring in a string.

Maximum palindrome substring

 

palindrome digits

Given an integer x, if x is a palindrome integer, return true; otherwise, return false.

A palindrome number is an integer that reads the same in forward order (from left to right) and reverse order (from right to left).
For example, 121 is a palindrome, but 123 is not.

Example 1:
Input: x = 121
Output: true
 
Example 2:
Input: x = -121
Output: false

Example 3:
Input: x = 10
Output: false
进阶:你能不将整数转为字符串来解决这个问题吗?

python implementation:
Idea: Reverse the integer and compare it with the original value. If they are equal, it will be True, otherwise it will be False.

class Solution:
    def isPalindrome(self, x: int) -> bool:
        # 负数不是
        if x < 0:
            return False
        # 单个数字 是回文
        elif x <= 9:
            return True

        else: # >= 10   O(n)
            origin = x
            reverse = 0
            base = 10
            while x // base: 
                base *= 10
            base /= 10

            while x:
                reverse += x % 10 * base
                x //= 10
                base /= 10 
            return reverse == origin

 

Maximum substring length without repeated characters

pending

 

valid parentheses

Given a string s that only includes '(', ')', '{', '}', '[', ']', determine whether the string is valid.

A valid string must satisfy:

  • The opening bracket must be closed by a closing bracket of the same type.
  • Opening brackets must be closed in the correct order.
  • Every right bracket has a corresponding left bracket of the same type.

Example 1:
Input: s = "()"
Output: true

Example 2:
Input: s = “()[]{}”
Output: true
 
Example 3:
Input: s = “(]”
Output: false

Tip:
1 <= s.length <= 104
s consists only of brackets '()[]{}'
 
python implementation:
hash + stack space

# hash存储对应关系
# 遍历字符串,左括号入栈
# 右括号出栈,并对比
class Solution:
    def isValid(self, s: str) -> bool:
        n = len(s)
        if n % 2 != 0:  # 有效则必然成对出现
            return False

        dict_ = {
    
      # 存储对应关系
            "(": ")",
            "[": "]",
            "{": "}",
            "0": "0"
        }

        stack = ["0"] # 防止第一个就是右括号,出栈报错
        for c in s:
            if c in dict_: # 左括号入栈
                stack.append(c)
            elif dict_[stack.pop()] != c: # 右括号出栈
                return False
        return len(stack) == 1             

 

Convert Roman Numerals to Integers

Roman numerals contain the following seven characters: I, V, X, L, C, D and M.

Character value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

For example, the Roman numeral 2 is written as II, 12 is written as XII, and 27 is written as XXVII.

Small numbers in Roman numerals are to the right of larger numbers. But there are special cases. For example, 4 is not written as IIII, but as IV. The number 1 is to the left of the number 5 and represents a number equal to the large number 5 minus the number 1, which is the value 4. Likewise, the number 9 is represented as IX. This special rule only applies to the following six situations:

I can be placed to the left of V (5) and X (10) to represent 4 and 9.
X can be placed to the left of L (50) and C (100) to represent 40 and 90.
C can be placed to the left of D (500) and M (1000) to represent 400 and 900.
Given a Roman numeral, convert it to an integer.

Example 1:
Input: s = “III”
Output: 3
 
Example 2:
Input: s = “IV”
Output: 4

Example 3:
Input: s = "IX"
Output: 9

Example 4:
Input: s = “LVIII”
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 5:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90, IV = 4.

python implementation

  • If the current symbol is greater than or equal to the symbol on the right, it is positive;
  • If the current symbol is smaller than the symbol to the right, it is negative.
class Solution:
    def romanToInt(self, s: str) -> int:
        dict_ = {
    
    
            "I": 1,
            "V": 5,
            "X": 10,
            "L": 50,
            "C": 100,
            "D": 500,
            "M": 1000
        }

        result = 0
        n = len(s)
        for i in range(n-1):
            c = s[i]
            if dict_.get(c) >= dict_.get(s[i+1]):
                # positive
                result += dict_.get(c)

            else:
                # negative
                result -= dict_.get(c)
        result += dict_.get(s[-1])

        return result

 

String wildcard

wildcardIt is a special syntax that is widely used in file search, databases, regular expressions and other fields.
Implement the following two wildcards:
*: Match 0 or more characters (Note: The characters that can be matched by * and ? only consist of letters and numbers 0 to 9)
? : Match 1 character

Note: Matching is not case sensitive.

enter:

  • wildcard expression;
  • A set of strings.

Output:

  • If the match is successful, true will be output.
  • If the match fails, false is output.

Advanced: Time complexity: O ( n 2 ) {O(n^2)}O ( n2 ), space complexity:O (n) {O(n)}O ( n )

 
Example 1
input:

  • The first line te?t*.*
  • The second line txt12.xls

Output:

  • false

 
Example 2
input:

  • First line z
  • Second linezz

Output:

  • false

 
Example 3
input:

  • pq
  • pppq

Output:

  • false

Example 4
input:

  • **z
  • 0QZz

Output:

  • true

Example 5
input:

  • ?*Bc*?
  • abcd

Output:

  • true

Example 6
input:

  • h*?*a
  • h#a

Output:

  • false

Example 7
input:

  • p*p*qp**pq*p**p***ppq
  • pppppppqppqqppqppppqqqppqppqpqqqppqpqpppqpppqpqqqpqqp

Output:

  • false

python implementation

  • s1, s2 are both empty;
  • There is an empty space in s1 and s2;
  • Neither s1 nor s2 is empty; solve it recursively from the last element.
  • When the last digit of s1 is a letter or number;
  • What is the last digit of s1? hour;
  • When the last digit of s1 is *;
# 匹配函数
def fun(s1, s2):
    if s1 == "" and s2 == "":
        return True
    elif s1 == "" and s2 != "":
        return False
    elif s1 != "" and s2 == "":
        if s1.replace("*", "") == "":
            return True
        else:
            return False
    else:
        m, n = len(s1), len(s2)
        if s1[m - 1] == s2[n - 1] or (s1[m - 1] == "?" and s2.isalnum()):
            return fun(s1[: m - 1], s2[: n - 1])

        elif s1[m - 1] == "*":
            return fun(s1[: m - 1], s2) or fun(s1, s2[: n - 1])
        else:
            return False


s1, s2 = input().lower(), input().lower()
if fun(s1, s2):
    print("true")
else:
    print("false")
    

have some problem.
 

Yang Hui triangle

Insert image description here
There is only one number 1 in the first line. Each number in each following line is the sum of the number above it, the number in the upper left corner and the number in the upper right corner. (If a certain number does not exist, it is considered that the number is 0).

Find the position of the first even number in line n. If there is no even number, then output -1
, input the nth line, and
output the position of the first even number in the nth line.
Example 1
input:
4
output:
3 which is 6 in the fourth row
python code

import sys
alt=[2,3,2,4] # 发现规律,从第三行开始偶数位置为2324循环
for line in sys.stdin:
    n=int(line.strip())
    if n<3:
        print(-1)
    if n>=3: 
        print(alt[(n-3)%4]) #所以对4求余,映射到上面alt列表中

 

Find the longest common substring in two strings a and b**

Advanced: Time complexity: O ( n 3 ) {O(n^3)}O ( n3 )
Space complexity:O ( n ) {O(n)}O ( n )
input:
input two strings

Output:
Return recurring characters

Example 1
input:
abcdefghijklmnop
abcsafjklmnopqrstuvw

Output:
jklmnop

python implementation
Traverse the short substring and determine whether it is in the long string.

def max_common_substring(a, b):
	if not a or not b:
        print("")
        return ""
    if len(a) > len(b):
        a, b = b, a
    res = ''
    # 遍历短的字符串
    for i in range(0, len(a)):
        for j in range(i, len(a)):
            if a[i:j + 1] in b:
                if j + 1 - i > len(res):
                    res = a[i:j + 1]
                    print(a[i:j + 1], "在")
            else:
                print(a[i:j + 1], "不在")
                break

    print(res)

 

Find the first character in a string that appears only once

find in stringFirstCharacters that appear only once

Input description:
Enter a non-empty string

Output description:
Output the first character that appears only once, if it does not exist, output -1

Example 1
input:
asdfasdfo

Output:
o
python implementation:

  • Hash counts the number of occurrences;
  • List records characters that appear once
def count_char(s):
    dict_ = {
    
    }
    temp = []
    for c in s:
        if c in dict_:
        	if c in temp:
            	temp.remove(c)
        else:
            dict_[c] = 1
            temp.append(c)
    if temp:
        print(temp[0])
        return temp[0]
    print(-1)
    return -1

s = input()
count_char(s)

 

represent numbers

Add the symbols "*" before and after all integers in a string, leaving other characters unchanged. Consecutive numbers are treated as an integer.
Enter description:
Enter a string

Output description:
Add the symbol "*" before and after all numbers that appear in the character, and other characters remain unchanged.

Example 1
Input:
Jkdi234klowe90a3
Copy
Output:
Jkdi 234 klowe 90 a 3

python implementation:

def add_star():
    s = input()
    s_o = ''
    char_pre = ''
    for i in s: #遍历字符串
        if i.isdigit() : #遇到数字,判断其前面是否非数字,是则表示数字的开始,先插入‘*’
            if not char_pre.isdigit():
                s_o +='*'
        else: #非数字情况,判断其前是否为数字,是则表示数字结束,插入‘*’
            if char_pre.isdigit():
                s_o +='*'
        s_o += i #把当前字符带出来
        char_pre = i #当前字符更新到 前字符
    if i.isdigit(): #结束的时候,判断是否数字结束,如果是的话,插入‘*’
        s_o +='*'
    print(s_o)
        

add_star()

 

Verify password is qualified

Password requirement:

1. The length exceeds 8 characters

2. Including uppercase and lowercase letters, numbers, and other symbols, at least three of the above four

3. There cannot be repeated substrings containing common elements with a length greater than 2 (note: other symbols do not include spaces or newlines)

Input Description:
An array of strings.
Output description:
Output that meets the requirements: OK, otherwise output NG

def check(s):
    if len(s) <= 8:
        return 0
    a, b, c, d = 0, 0, 0, 0
    for item in s:
        if ord('a') <= ord(item) <= ord('z'):
            a = 1
        elif ord('A') <= ord(item) <= ord('Z'):
            b = 1
        elif ord('0') <= ord(item) <= ord('9'):
            c = 1
        else:
            d = 1
    if a + b + c + d < 3:
        return 0
    for i in range(len(s)-3):
        if len(s.split(s[i:i+3])) >= 3:
            return 0
    return 1


s = input()
print('OK' if check(s) else 'NG')

 

String encryption

There is a trick to encrypt data that uses a word as its key. Here's how it works: First, choose a word as the key, such as TRAILBLAZERS. If the word contains repeated letters, only the first one is retained, the result is used as the beginning of the new alphabet, and the letters that do not appear in the newly created alphabet are added to the new alphabet in normal alphabetical order. It looks like this:
ABCDEFGHIJKLMNOPQRSTU VWXYZ

TRAILBZESCDFGHJKMNOPQ UVWXY (Actually, an alphabet of lowercase letters needs to be created, this alphabet is only for convenience of demonstration)

The others above are filled in completely with the remaining letters of the alphabet. When a message is encrypted, each letter in the message is fixed to the top row and the letters of the original text are replaced one by one with the corresponding letters of the lower row (the upper and lower case status of the alphabetic characters should be preserved). Therefore, using this key, Attack AT DAWN will be encrypted as Tpptad TP ITVH.

Please implement the following interface to obtain the ciphertext through the specified key and plaintext.

Ensure that the input string contains only lowercase letters

Input description:
First enter the key and the string to be encrypted

Output description:
Returns the encrypted string

Example 1
input:
nihao
ni

Output:
le

Guess you like

Origin blog.csdn.net/weixin_45228198/article/details/132144364