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/


目录
相关文章
|
17天前
|
Java API Apache
Java编程如何读取Word文档里的Excel表格,并在保存文本内容时保留表格的样式?
【10月更文挑战第29天】Java编程如何读取Word文档里的Excel表格,并在保存文本内容时保留表格的样式?
75 5
|
1月前
|
存储 算法 搜索推荐
探索常见数据结构:数组、链表、栈、队列、树和图
探索常见数据结构:数组、链表、栈、队列、树和图
101 64
|
3月前
【bug记录】旋转链表与力扣报错:member access within null pointer of type ‘struct ListNode‘
【bug记录】旋转链表与力扣报错:member access within null pointer of type ‘struct ListNode‘
|
1月前
|
Python
Python对PDF文件页面的旋转和切割
Python对PDF文件页面的旋转和切割
|
2月前
|
Java
java基础(10)数据类型中的整数类型
Java中的整数类型包括byte、short、int和long。整数字面值默认为int类型,加L表示long类型。整数字面值可以是十进制、八进制(0开头)或十六进制(0x开头)。小容量类型(如int)可自动转换为大容量类型(如long),但大容量转小容量需强制转换,可能导致精度损失。
42 2
|
1月前
|
存储
一篇文章了解区分指针数组,数组指针,函数指针,链表。
一篇文章了解区分指针数组,数组指针,函数指针,链表。
18 0
|
3月前
|
Python
【Leetcode刷题Python】114. 二叉树展开为链表
LeetCode上114号问题"二叉树展开为链表"的Python实现,通过先序遍历二叉树并调整节点的左右指针,将二叉树转换为先序遍历顺序的单链表。
27 3
【Leetcode刷题Python】114. 二叉树展开为链表
|
3月前
|
Python
【Leetcode刷题Python】剑指 Offer 22. 链表中倒数第k个节点
Leetcode题目"剑指 Offer 22. 链表中倒数第k个节点"的Python解决方案,使用双指针法找到并返回链表中倒数第k个节点。
54 5
|
3月前
|
Python
【Leetcode刷题Python】剑指 Offer 18. 删除链表的节点
Leetcode题目"剑指 Offer 18. 删除链表的节点"的Python解决方案,通过使用双指针法找到并删除链表中值为特定数值的节点,然后返回更新后的链表头节点。
41 4
|
3月前
|
Python
【Leetcode刷题Python】剑指 Offer 11. 旋转数组的最小数字
解决剑指Offer 11题 "旋转数组的最小数字" 的三种Python实现方法:直接使用min函数、线性查找分界点和二分查找法,以找出旋转数组中的最小元素。
54 2