zoukankan      html  css  js  c++  java
  • 判断字符串是否回文

    设计思路:

    递归判断 字符串的首尾位置的字符是否一样。

    遇到的问题:

    用 Scanner input=new Scanner(System.in);

    实例化一个对象,用完不关闭会一直占用资源,编译时会警告。

    应关闭 :input.close();

    源代码:

    package Huiwen;

    import java.util.*;
    public class Palindrome
    {
    public static void main(String[] args)
    {
    System.out.println("请输入一个字符串:");
    Scanner input=new Scanner(System.in); //扫描从控制台输入的字符
    String str=input.nextLine(); //输入字符串
    int n=str.length();
    int m=JudgePalindrome(str,n);
    if(m==1)
    System.out.println("该字符串回文");
    else
    System.out.println("该字符串不回文");
    input.close();
    }

    public static int JudgePalindrome(String str,int n)
    {
    int s,w;
    int j=0;
    char c1,c2;
    s=str.length()-n;//第一个字符的位置
    w=n-1;//最后一个字符的位置
    c1=str.charAt(s);//stringObject.charAt(index) 方法可返回指定位置的字符
    c2=str.charAt(w);//字符串中第一个字符的下标是 0。如果参数 index 不在 0 与 string.length 之间,该方法将返回一个空字符串。
    if(c1==c2||s==w)
    j=1;
    if(s!=w&&s<w&&j==1)
    JudgePalindrome(str,n-1);
    return j;
    }
    }

    运行结果截图:

  • 相关阅读:
    python简单文件服务器
    Qt5WebSockets
    cartographer ros 配置项
    ubuntu18.04 evo 测评工具安装
    ubuntu18.04 orb_slam2安装记录
    clonezilla使用说明
    会计报名
    将博客搬至CSDN
    JS--微信浏览器复制到剪贴板实现
    Python--Django学习笔记2
  • 原文地址:https://www.cnblogs.com/janeszj/p/9781712.html
Copyright © 2011-2022 走看看