最后一個單詞的長度
給你一個字串 s,由若干單詞組成,單詞前后用一些空格字符隔開,回傳字串中最后一個單詞的長度,
單詞 是指僅由字母組成、不包含任何空格字符的最大子字串,
示例 1:
輸入:s = “Hello World”
輸出:5
示例 2:
輸入:s = " fly me to the moon "
輸出:4
示例 3:
輸入:s = “luffy is still joyboy”
輸出:6
提示:
1 <= s.length <= 104
s 僅有英文字母和空格 ’ ’ 組成
s 中至少存在一個單詞
class Solution {
public int lengthOfLastWord(String s) {
int end=s.length()-1;
while(end>=0&&s.charAt(end)==' ') end--;
if(end<0) return 0;
int start=end;
while(start>=0&&s.charAt(start)!=' ') start--;
return end-start;
}
}
實作呼叫:
package com.kk;
import java.util.Scanner;
public class LengthOfLastWord {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = new String();
s=scanner.nextLine();
int i = lengthOfLastWord(s);
System.out.println(i);
}
public static int lengthOfLastWord(String s) {
int end=s.length()-1;
while(end>=0&&s.charAt(end)==' ') end--; //如果末尾是空格 使用end 過濾
if (end<0) return 0;
int start =end;
while (start>=0&&s.charAt(start)!=' ') start--;
return end-start;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/342030.html
標籤:其他
上一篇:常見的業務邏輯漏洞-整合篇
