• Reverse Word in a String(翻转字符串)&字符串最后一个单词的长度


    1.题目:

    Given an input string, reverse the string word by word.

    For example,
    Given s = "the sky is blue",
    return "blue is sky the".

    运用到了栈的思想。先进后出,这样就逆序了。

     时间复杂度,就是整个程序在运行过程中,每个小模块运行的次数之和。

     时间复杂度指运行时间需求,空间复杂度是指运行空间需求。

    public class toChar1{
    	public static void main(String[] args){
    		String s1="I am a student";
    		char[] arr=s1.toCharArray();
    		for(int i=arr.length-1;i>=0;i--){
    			System.out.print(arr[i]);
    		}
    	}
    }
    

    2.计算字符串最后一个单词的长度,单词以空格隔开。

    描述

    计算字符串最后一个单词的长度,单词以空格隔开。

    知识点 字符串,循环
    运行时间限制 0M
    内存限制 0
    输入

    一行字符串,长度小于128。

    输出

    整数N,最后一个单词的长度。

    样例输入 hello world
    样例输出 5

      

    import java.util.Scanner;
    
    public class Main{    
        public static void main(String[] args) { 
             int i;
            // System.out.println("请输入字符串:");  
             Scanner scStr = new Scanner(System.in); //从键盘获取字符串  
             String str = scStr.nextLine();          //将Scanner对象中的内容以字符串的形式取出来  
             char arr[]=str.toCharArray();
             for( i=arr.length-1;i>=0;i--){
                 if(arr[i]==' ')
                 break;
             }    
             int length=arr.length-i;
             char shuchu[]=new char[length-1]  ;int k=0;
            
             for(int j=i+1;j<=arr.length-1;j++){
                 shuchu[k]=arr[j];    k++;        
             }
            // System.out.println("最后一个单词为:");
             System.out.println(k);
        }     
    }

    nextInt() :接受从键盘输入的int数据

    (2)hasNextInt(); 判断是否输入为整型 int 

    (3)nextLine():   返回按 enter键 之前输入的字符

  • 相关阅读:
    pat00-自测5. Shuffling Machine (20)
    Spiral Matrix
    Search in Rotated Sorted Array II
    Search in Rotated Sorted Array
    Best Time to Buy and Sell Stock II
    4Sum
    3Sum Closest
    3Sum
    MySQL存储过程、函数和游标
    Word Ladder
  • 原文地址:https://www.cnblogs.com/GumpYan/p/5730826.html
Copyright © 2020-2023  润新知