这里写目录标题
字符串
本章节代码部分参考自网络,部分由自己编写,但都已得到验证,均可正确执行。
1. 最后一个字的长度【Length of Last Word】
题目:给定一个由大/小写字母和空位字符’'组成的字符串s。返回字符串中最后一个字的长度
- 如果最后一个字不存在,返回0。
- 注意:一个词被定义为一个仅由非空格字符组成的字符序列。
- 例如,s = “Hello World”,返回5。
解析:这道题主要是考虑一下最后是不是空格,方法是倒着找不是空格的字符并计数,首先我们需要去掉首尾的空格,然后以空格去分割字符串,得到最后一个单词,最后得到其长度。
Python 代码
def length_of_last_word(s):
"""
:type s: str
:rtype: int
"""
# strip()方法用于移除字符串头尾指定的字符(如果括号内没有指定字符,默认为空格)或字符序列
# split()按照括号内给定的字符进行分割,默认的按照空格进行分割。返回一串字符串列表,
word_list = s.strip().split(' ')
print(word_list)
last_word = word_list[-1]
return len(last_word)
if __name__ == '__main__':
s1 = " Hello World "
last_word_len = length_of_last_word(s1)
print(last_word_len)
输出:
['Hello', 'World']
5
java 代码
for 循环只是为了方便查看,列表内容,便于理解,做题时,应该删除。
public int lengthOfLastWord(String s) {
//trim()方法用于删除字符串的头尾空白符,与python不同,trim()没有参数。
String[] words = s.trim().split(" ");
for (int i = 0; i < words.length; i++) {
System.out.println(words[i]);
}
int len = words[words.length - 1].length();
return len;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String_Solution solution = new String_Solution();
String string = " hello world ";
System.out.println(solution.lengthOfLastWord(string));
}
输出:
hello
world
5
2. 简化路径【Simplify Path】
题目:给出一个文件的绝对路径(Unix风格),将其简化。例如:
- path = “/home/”, => “/home”
- path = “/a/./b/…/…/c/”, => “/c”
你考虑过path ="/./"
的情况吗?在这种情况下,你应该返回 "/"
。
另一个案例是路径可能包含多个斜线’/'在一起,例如 "/home/foo/"
。在这种情况下,你应该忽略多余的斜线并返回 "/home/foo"
。
Python 实现
# 方法一:利用python的split()函数
def simplify_path(path):
# /a/./b/../../c/
# 将/作为划分标志,转化为 list ['', 'a', '.', 'b','..', '..', 'c', '']
path = path.split('/')
curr = '/'
for character in path:
if character == '..': # 上一目录
if curr != '/': # 如果curr不是根目录
curr = '/'.join(curr.split('/')[:-1]) # 就去掉末尾的字符。字符之间用'/'连接
if curr == '':
curr = '/'
elif character != '.' and character != '': # 不是当前目录
if curr != '/': # 不是根目录,就加一个 / 与字符连接
curr += '/' + character
else: # 是根目录就直接加字符
curr += character
return curr
if __name__ == '__main__':
paths = "/a/./b/../../c/"
print(simplify_path(paths))
# 使用栈的方法进行操作
def simplify_paths(path):
parts = path.split("/")
stack = ['']
for part in parts:
if part: # 判断part是不是空字符
if part not in ('.', '..'): # 1. part 不为空,也不是当前目录和上一目录
if len(stack) == 0: # 若栈底空了,即 part为根目录'/'下的子目录 需要先加入空字符再加入目录名
stack.append('')
stack.append(part) # 将字符入栈
elif part == '..' and len(stack) > 0: # 2. part是..则需要出栈,.当前目录不操作。
stack.pop()
if len(stack) < 2: # stack = 1,即根目录
return "/"
else:
return "/".join(stack) # 以/来拼接list里的字符
if __name__ == '__main__':
paths = "/home/foo/"
print(simplify_paths(paths))
Java 实现
public static String simplify_path(String str) {
String[] s = str.split("/"); // "/a/b/c/"; // 输出 " ", "a", "b", "c"
StringBuffer sb = new StringBuffer();
sb.append("/");
// StringBuffer没有重写equal(),所以想要进行值比较需要先转化String.
for (int i = 0; i < s.length; i++) {
if (s[i].equals("..")) { //返回上一级目录
if (!sb.toString().equals("/")) {// sb不是根目录
sb.deleteCharAt(sb.length()-1);
sb.deleteCharAt(sb.length()-1);
}
}
else if (!s[i].equals(".") && !s[i].equals(" ")) {
if (!sb.toString().equals("/")) {
sb.append("/");
sb.append(s[i]);
}
else {
sb.append(s[i]);
}
}
}
return sb.toString();
}
public static void main(String[] args) {
String s1 = "/home/"; // 输出 " ", "a", "b", "c"
System.out.println(Solution.simplify_path(s1));
}
3. 报数【Count and Say】
报数序列是以下列方式开始的整数序列。1, 11, 21, 1211, 111221, …
- 1被读作 "一个1 "或11。
- 11被读作 "两个1 "或21。
- 21被读作 "一个2,然后一个1 "或1211。
给定数据的规律为:每一行的内容为上一行的数字串从左到右读出来。
思路:
- 由于每一行的内容为前一行的内容从左到右顺序读出,而且需要统计每个数字出现的次数(
相邻数字一样,累加统计
)。 - 所以要都读出的内容必须是字符型(char),不能是数字类型(int,float等)否则无法进行统计数字出现次数。 通过循环来进行统计读出。
Python 实现
def count_and_say(n):
"""
:type n: int
:rtype: str
"""
b = '1' # 将第一行的1换成字符类型,便于下一行的读出
for i in range(n - 1): # (n-1)是因为第一行不需要处理,直接可以读出
a, c, count = b[0], '', 0 # a 用来读取上一行的字符,c用来存放读出的内容(char),count用来统计相邻a出现的次数
for j in b:
if a == j:
count += 1
else:
c += str(count) + a # 注意一定要将count转换为字符型,否则两个数就会相加(变成数学公式)。
a = j
count = 1
c += str(count) + a
b = c
return b
if __name__ == '__main__':
temp_n = 4 # 1, 11, 21, 1211
print(count_and_say(temp_n))
Java 实现
public static String countAndsay(int n) {
String x = "1"; // n=3 return 21
for (int i = 1; i < n; i++) {
char a = x.charAt(0); // a 用来读取上一行的字符.
String s = ""; // s 用来存放读出的内容
int count = 0; //count用来统计相邻a出现的次数
for (int j = 0; j < x.length(); j++) {
if (a==x.charAt(j)) {
count++;
}
else {
s = s + String.valueOf(count) + a;
a = x.charAt(j);
count = 1;
}
}
s = s + String.valueOf(count) + a;
x = s;
}
return x;
}
public static void main(String[] args) {
System.out.println(Solution.countAndsay(3));
}
4. 整数与罗马数相互转换【 Integer to Roman】
通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:
I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。
C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。
给定一个罗马数字,将其转换成整数。
右加左减
:
- 在较大的罗马数字的右边记上较小的罗马数字,表示大数字加小数字。
- 在较大的罗马数字的左边记上较小的罗马数字,表示大数字减小数字。
- 左减的数字有限制,仅限于I、X、C。比如45不可以写成VL,只能是XLV
- 但是,左减时不可跨越一个位值。
- 比如,99不可以用IC(100-1)表示,而是用XCIX( [100-10]+[10-1])表示。
def int_to_roman(num: int) -> str:
intToRoman = [(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),
(100, "C"), (90, "XC"), (50, "L"), (40, "XL"),
(10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I")]
# 用来保存整数转罗马数字的信息
roman_num = ""
for number, roman in intToRoman:
# divmod()函数接收两个数字类型(非复数)参数,返回一个包含商和余数的元组(a // b, a % b)
# 用来保存整数和余数部分
# 整数表示重复的次数
count, num = divmod(num, number)
print("count={},num={}".format(count, num))
roman_num += roman * count
# 当余数为0时结束循环
if num == 0:
break
return roman_num
if __name__ == '__main__':
print(int_to_roman(3))
def roman_to_int(s: str) -> int:
d = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
r = [0] # 创建一个列表 r,在遍历字符串时存储要累加的值
for i in s:
l = r[-1] # 变量 l 为 r 的最后一个元素
if d[i] > l: # 若当前数字大于 l,则说明出现了题目所说的特例
r[-1] = -l # 将上一个数字转为负数
r.append(d[i]) # 将当前数字加入列表
print(r)
return sum(r)
if __name__ == '__main__':
print(roman_to_int("CII"))
print(roman_to_int("IV"))
IV就是上面的特例:
第一次for循环:r[-1]=0;d[i] = d[I] = 1;r[-1] = -0 人 ==》[-0,1]
第二次for循环:r[-1]=1;d[i] = d[V] = 5;r[-1] = -1 人 ==》[-0,-1,5]
输出:
[0, 100, 1, 1]
102
[0, -1, 5]
4
5. 括号匹配
给定一个字符串str,判断是不是整体有效的括号字符串(整体有效:即存在一种括号匹配方案,使每个括号字符均能找到对应的反向括号,且字符串中不包含非括号字符)。
import java.util.Scanner;
public class Main {
public static boolean judge_kuohao(String str) {
if(str == null||str.length()==0){
return false;
}
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i)=='(') {
count++;
}
if (str.charAt(i)==')') {
count=count-1;
if(count<0){
return false;
}
}
if(str.charAt(i)!=')' && str.charAt(i)!='('){
return false;
}
}
if (count!=0) {
return false;
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
//boolean b = Main.judge_kuohao(s);
if(Main.judge_kuohao(s))
System.out.println("YES");
else
System.out.println("NO");
}
}