Java每日一练(20230430) 文本左右对齐、素数和、整数转英文表示

简介: Java每日一练(20230430) 文本左右对齐、素数和、整数转英文表示

1. 文本左右对齐

给定一个单词数组和一个长度 maxWidth,重新排版单词,使其成为每行恰好有 maxWidth 个字符,且左右两端对齐的文本。

你应该使用“贪心算法”来放置给定的单词;也就是说,尽可能多地往每行中放置单词。必要时可用空格 ' ' 填充,使得每行恰好有 maxWidth 个字符。

要求尽可能均匀分配单词间的空格数量。如果某一行单词间的空格不能均匀分配,则左侧放置的空格数要多于右侧的空格数。

文本的最后一行应为左对齐,且单词之间不插入额外的空格。

说明:

  • 单词是指由非空格字符组成的字符序列。
  • 每个单词的长度大于 0,小于等于 maxWidth
  • 输入单词数组 words 至少包含一个单词。

示例:

输入:

words = ["This", "is", "an", "example", "of", "text", "justification."]

maxWidth = 16

输出:

[
   "This    is    an",
   "example  of text",
   "justification.  "
]

示例 2:

输入:

words = ["What","must","be","acknowledgment","shall","be"]

maxWidth = 16

输出:

[
  "What   must   be",
  "acknowledgment  ",
  "shall be        "
]

解释: 注意最后一行的格式应为 "shall be    " 而不是 "shall     be"

因为最后一行应为左对齐,而不是左右两端对齐,第二行同样为左对齐,这是因为这行只包含一个单词。


示例 3:

输入:

words = ["Science","is","what","we","understand","well","enough","to","explain",

        "to","a","computer.","Art","is","everything","else","we","do"]

maxWidth = 20

输出:

[
  "Science  is  what we",
  "understand      well",
  "enough to explain to",
  "a  computer.  Art is",
  "everything  else  we",
  "do                  "
]


以下程序实现了这一功能,请你填补空白处内容:

```Java
class Solution {
    public List fullJustify(String[] words, int maxWidth) {
        List ret = new ArrayList<>();
        int index = 0;
        while (index < words.length) {
            int cur = index, len = 0;
            while (cur < words.length && len + words[cur].length() + cur - index <= maxWidth) {
                len = len + words[cur++].length();
            }
            cur--;
            StringBuilder sb = new StringBuilder();
            if (cur == words.length - 1) {
                for (int i = index; i <= cur; i++) {
                    sb.append(words[i]);
                    if (i < cur) {
                        sb.append(' ');
                    }
                }
            } else {
                int base = cur > index ? (maxWidth - len) / (cur - index) : (maxWidth - len);
                String baseStr = genSpace(base);
                int left = cur > index ? (maxWidth - len) % (cur - index) : 0;
                String leftStr = genSpace(base + 1);
                for (int i = index; i <= cur; i++) {
                    sb.append(words[i]);
                    ___________________;
                }
            }
            if (sb.length() < maxWidth) {
                sb.append(genSpace(maxWidth - sb.length()));
            }
            ret.add(sb.toString());
            index = cur + 1;
        }
        return ret;
    }
    private String genSpace(int n) {
        char[] cs = new char[n];
        Arrays.fill(cs, ' ');
        return new String(cs);
    }
}
```

出处:

https://edu.csdn.net/practice/26880552

代码:

import java.util.*;
public class fullJustify {
    public static class Solution {
        public List<String> fullJustify(String[] words, int maxWidth) {
            List<String> ret = new ArrayList<>();
            int index = 0;
            while (index < words.length) {
                int cur = index, len = 0;
                while (cur < words.length && len + words[cur].length() + cur - index <= maxWidth) {
                    len = len + words[cur++].length();
                }
                cur--;
                StringBuilder sb = new StringBuilder();
                if (cur == words.length - 1) {
                    for (int i = index; i <= cur; i++) {
                        sb.append(words[i]);
                        if (i < cur) {
                            sb.append(' ');
                        }
                    }
                } else {
                    int base = cur > index ? (maxWidth - len) / (cur - index) : (maxWidth - len);
                    String baseStr = genSpace(base);
                    int left = cur > index ? (maxWidth - len) % (cur - index) : 0;
                    String leftStr = genSpace(base + 1);
                    for (int i = index; i <= cur; i++) {
                        sb.append(words[i]);
                        if (i < cur) {
                            sb.append(left > 0 ? leftStr : baseStr);
                            left--;
                        }
                    }
                }
                if (sb.length() < maxWidth) {
                    sb.append(genSpace(maxWidth - sb.length()));
                }
                ret.add(sb.toString());
                index = cur + 1;
            }
            return ret;
        }
        private String genSpace(int n) {
            char[] cs = new char[n];
            Arrays.fill(cs, ' ');
            return new String(cs);
        }
    }
    public static void main(String[] args) {
        Solution sol = new Solution();
        String[] words = {"This", "is", "an", "example", "of", "text", "justification."};
        int maxWidth = 16;
        for (String str : sol.fullJustify(words, maxWidth)) {
            System.out.println("["+str+"]");
        }
        String[] words2 = {"What","must","be","acknowledgment","shall","be"};
        for (String str : sol.fullJustify(words2, maxWidth)) {
            System.out.println("["+str+"]");
        }
        String[] words3 = {"Science","is","what","we","understand","well","enough","to","explain",
            "to","a","computer.","Art","is","everything","else","we","do"};
        maxWidth = 20;
        for (String str : sol.fullJustify(words3, maxWidth)) {
            System.out.println("["+str+"]");
        }
    }
}

输出:

[This    is    an]
[example  of text]
[justification.  ]
[What   must   be]
[acknowledgment  ]
[shall be        ]
[Science  is  what we]
[understand      well]
[enough to explain to]
[a  computer.  Art is]
[everything  else  we]
[do                  ]

2. 求素数

求第m个到第n个素数之间的素数和

出处:

https://edu.csdn.net/practice/26880553

代码:

import java.util.Scanner;
public class All {
   public static void main(String[] args) {
      int a[] = new int[200];
      int index = 0;
      for (int i = 1; i < 200; i++) {
         boolean isPrime = true;
         for (int k = 2; k < i; k++) {
            if (i % k == 0) {
               isPrime = false;
               break;
            }
         }
         if (isPrime) {
            a[index++] = i;
            System.out.println(a[index - 1]);
         }
      }
      Scanner small = new Scanner(System.in);
      Scanner large = new Scanner(System.in);
      int m = small.nextInt();
      int n = large.nextInt();
      int sums = 0;
      int suml = 0;
      int sum = 0;
      for (int i = 0; i < m; i++) {
         sums += a[i];
         System.out.print(a[i] + "*");
      }
      for (int i = 0; i < n; i++) {
         suml += a[i];
         System.out.print(a[i] + " ");
      }
      sum = suml - sums;
      System.out.println(sum);
   }
}

输出:


3. 整数转换英文表示

将非负整数 num 转换为其对应的英文表示。

示例 1:

输入:num = 123

输出:"One Hundred Twenty Three"


示例 2:

输入:num = 12345

输出:"Twelve Thousand Three Hundred Forty Five"


示例 3:

输入:num = 1234567

输出:"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"


示例 4:

输入:num = 1234567891

输出:"One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"


提示:

  • 0 <= num <= 2^31 - 1

出处:

https://edu.csdn.net/practice/26880554

代码:

import java.util.*;
public class numberToWords {
    public static class Solution {
        String[] withinTwentyNum = new String[] { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
                "Nine", "Ten",
                "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
        String[] theWholeTen = new String[] { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty",
                "Ninety" };
        String[] unit = new String[] { "", "Thousand", "Million", "Billion" };
        public String numberToWords(int num) {
            if (num == 0) {
                return withinTwentyNum[num];
            }
            StringBuilder sb = new StringBuilder();
            int unitCount = 0;
            int temp;
            String[] words = new String[32];
            int wordIndex = 0;
            for (int n = num; num > 0; unitCount++) {
                n = num % 1000;
                num /= 1000;
                if (n == 0) {
                    continue;
                }
                words[wordIndex++] = unit[unitCount];
                temp = n % 100;
                if (n % 100 > 0) {
                    if (temp >= 20) {
                        if (temp % 10 > 0) {
                            words[wordIndex++] = withinTwentyNum[temp % 10];
                        }
                        words[wordIndex++] = theWholeTen[temp / 10];
                    } else {
                        words[wordIndex++] = withinTwentyNum[temp];
                    }
                }
                temp = n / 100;
                if (temp > 0) {
                    words[wordIndex++] = "Hundred";
                    words[wordIndex++] = withinTwentyNum[temp];
                }
            }
            for (int index = wordIndex - 1; index >= 0; index--) {
                sb.append(words[index]).append(" ");
            }
            return sb.toString().trim();
        }
    }
    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(sol.numberToWords(123));
        System.out.println(sol.numberToWords(12345));
        System.out.println(sol.numberToWords(1234567));
        System.out.println(sol.numberToWords(1234567891));
    }
}

输出:

One Hundred Twenty Three

Twelve Thousand Three Hundred Forty Five

One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven

One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One


🌟 每日一练刷题专栏 🌟

持续,努力奋斗做强刷题搬运工!

👍 点赞,你的认可是我坚持的动力!

🌟 收藏,你的青睐是我努力的方向!

评论,你的意见是我进步的财富!  

主页:https://hannyang.blog.csdn.net/


目录
相关文章
|
3月前
|
Java 数据处理 索引
(Pandas)Python做数据处理必选框架之一!(二):附带案例分析;刨析DataFrame结构和其属性;学会访问具体元素;判断元素是否存在;元素求和、求标准值、方差、去重、删除、排序...
DataFrame结构 每一列都属于Series类型,不同列之间数据类型可以不一样,但同一列的值类型必须一致。 DataFrame拥有一个总的 idx记录列,该列记录了每一行的索引 在DataFrame中,若列之间的元素个数不匹配,且使用Series填充时,在DataFrame里空值会显示为NaN;当列之间元素个数不匹配,并且不使用Series填充,会报错。在指定了index 属性显示情况下,会按照index的位置进行排序,默认是 [0,1,2,3,...] 从0索引开始正序排序行。
353 0
|
9月前
|
存储 Python
Python 中链表的个人理解
简介:本文介绍了Python中链表的基本组成及其操作实现。链表由`head`(头节点)、中间节点和`tail`(尾节点)三部分构成,每个节点通过`Node`类定义,包含`value`(值域)和`next`(指针域)。示例代码展示了链表的增删查功能,包括`add`(头部插入)、`append`(尾部插入)、`remove`(删除节点)、`search`(查找节点)及遍历方法。运行结果验证了链表操作的正确性。
|
11月前
|
存储 Python
Python 实现单向链表,和单向链表的反转
链表是一种数据结构,每个节点存储相邻节点的位置信息。单链表中的节点仅存储下一节点的位置。通过Python实现单链表,定义`ListNode`类并关联节点可创建链表。例如,创建A-&gt;B-&gt;C的链表后,可通过反转函数`reverse`将链表反转为CBA。代码展示了如何实现和操作单链表。
268 6
Python 实现单向链表,和单向链表的反转
|
算法 数据安全/隐私保护 开发者
马特赛特旋转算法:Python的随机模块背后的力量
马特赛特旋转算法是Python `random`模块的核心,由松本真和西村拓士于1997年提出。它基于线性反馈移位寄存器,具有超长周期和高维均匀性,适用于模拟、密码学等领域。Python中通过设置种子值初始化状态数组,经状态更新和输出提取生成随机数,代码简单高效。
378 63
|
数据挖掘 数据处理 开发者
Python3 自定义排序详解:方法与示例
Python的排序功能强大且灵活,主要通过`sorted()`函数和列表的`sort()`方法实现。两者均支持`key`参数自定义排序规则。本文详细介绍了基础排序、按字符串长度或元组元素排序、降序排序、多条件排序及使用`lambda`表达式和`functools.cmp_to_key`进行复杂排序。通过示例展示了如何对简单数据类型、字典、类对象及复杂数据结构(如列车信息)进行排序。掌握这些技巧可以显著提升数据处理能力,为编程提供更强大的支持。
683 10
|
存储 算法 搜索推荐
探索常见数据结构:数组、链表、栈、队列、树和图
探索常见数据结构:数组、链表、栈、队列、树和图
588 64
|
11月前
|
存储 算法 搜索推荐
Python 实现反转、合并链表有啥用?
大家好,我是V哥。本文介绍Python实现反转链表和合并链表的应用场景及代码实现。反转链表适用于时间序列数据展示、回文链表判断等;合并链表则用于大规模数据排序、数据库查询结果集合并等。通过迭代和递归方法实现反转链表,以及合并两个或多个有序链表的算法,帮助开发者解决实际问题。关注V哥,了解更多实用编程技巧。 先赞再看后评论,腰缠万贯财进门。
233 0
|
存储 缓存 算法
在C语言中,数据结构是构建高效程序的基石。本文探讨了数组、链表、栈、队列、树和图等常见数据结构的特点、应用及实现方式
在C语言中,数据结构是构建高效程序的基石。本文探讨了数组、链表、栈、队列、树和图等常见数据结构的特点、应用及实现方式,强调了合理选择数据结构的重要性,并通过案例分析展示了其在实际项目中的应用,旨在帮助读者提升编程能力。
427 5
|
Python
探索 Python 中链表的实现:从基础到高级
链表是一种由节点组成的基础数据结构,每个节点包含数据和指向下一个节点的引用。本文通过Python类实现单向链表,详细介绍了创建、插入、删除节点等操作,并提供示例代码帮助理解。链表在处理动态数据时具有高效性,适用于大量数据变动的场景。文章为初学者提供了全面的入门指南,助你掌握链表的核心概念与应用。
661 0
|
搜索推荐 Python
快速排序的 Python 实践:从原理到优化,打造你的排序利器!
本文介绍了 Python 中的快速排序算法,从基本原理、实现代码到优化方法进行了详细探讨。快速排序采用分治策略,通过选择基准元素将数组分为两部分,递归排序。文章还对比了快速排序与冒泡排序的性能,展示了优化前后快速排序的差异。通过这些分析,帮助读者理解快速排序的优势及优化的重要性,从而在实际应用中选择合适的排序算法和优化策略,提升程序性能。
407 1

推荐镜像

更多