Algorithm-String

本文介绍了几种字符串操作的方法,包括字符串位移、链表节点反转等,并提供了一个将字符串转换为整数的实现及测试案例。代码示例涵盖了字符串处理的多种应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Algorithm-String

通过翻转来位移

  • 字符串

    public class LeftShift {
      void StringReverse(char[] strs, int start, int end) {
        char tmp;
        while (end > start) {
          tmp = strs[start];
          strs[start++] = strs[end];
          strs[end--] = tmp;
        }
      }
    
      public String stringShiftLeft(String str, int m) {
        char[] strs = str.toCharArray();
        m %= str.length();
        StringReverse(strs, 0, m - 1);
        StringReverse(strs, m, str.length() - 1);
        StringReverse(strs, 0, str.length() - 1);
        return new String(strs);
      }
    
    
  • 链表

     Node listReverse(Node root, int start, int end) {
        Node head = new Node(0);
        head.next = root;
        Node pre = head;
        for (int i = 0; i < start - 1; i++) {
          pre = pre.next;
        }
        Node node = pre.next;
        Node post = node.next;
        for (int i = 0; i < end - start; i++) {
          node.next = post.next;
          post.next = pre.next;
          pre.next = post;
          post = node.next;
        }
        return head.next;
      }
    
      public Node listRotate(Node root, int walk) {
        Node node = root;
        int len = 0;
        while (node != null) {
          len++;
          node = node.next;
        }
        root = listReverse(root, 1, walk);
        root = listReverse(root, walk + 1, len);
        return root;
      }
    

26个字目HASH

boolean stringContain(String str1, String str2) {
    int hash = 0;
    String str = str1.toUpperCase();
    for (int i = 0; i < str.length(); i++) {
      hash |= (1 << (str.charAt(i) - 'A'));
    }
    str = str2.toUpperCase();
    for (int i = 0; i < str2.length(); i++) {
      if ((hash & (1 << (str.charAt(i) - 'A'))) == 0) {
        return false;
      }
    }
    return true;
  }

String To Integer

 // sign must be initialized,may be some value not contains '+', which means '+'
    int sign = 1, digit, index = 0, total = 0;
    //empty string
    if (str.length() == 0) {
      return 0;
    }
    //remove space, should not to use trim
    while (index < str.length() && str.charAt(index) == ' ') {
      index++;
    }

    //handle sign
    if (str.charAt(index) == '+' || str.charAt(index) == '-') {
      sign = str.charAt(index) == '+' ? 1 : -1;
      index++;
    }
    //convert string to number
    while (index < str.length()) {
      digit = str.charAt(index++) - '0';
      //exception
      if (digit < 0 || digit > 9) {
        break;
      }
      //avoid overflow
      if (total > Integer.MAX_VALUE / 10 || total == Integer.MAX_VALUE / 10 && digit > 7) {
        return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
      }
      total = total * 10 + digit;
    }
    return total * sign;

test case

@RunWith(Parameterized.class)
public class StringToIntegerTest {
  private StringToInteger solution;

  @Parameter
  public String input;
  @Parameter(1)
  public int output;

  public static final Object[][] test = {
    {"1230", 1230},
    {"123", 123},
    {"-321809", -321809},
    {"+", 0},
    {"-", 0},
    {"+12309", 12309},
    {"-1239", -1239},
    {"123a76", 123},
    {"12345678987654321",Integer.MAX_VALUE},
    {"-12345678987654321",Integer.MIN_VALUE}
  };

  @Parameters(name = "{index}")
  public static Iterable<Object[]> tests() {
    return Arrays.asList(test);
  }

  @Before
  public void setUp() throws Exception {
    solution = new StringToInteger();
  }

  @Test
  public void strToInt() throws Exception {
    assertThat(solution.StrToInt(input), is(output));
  }
}

转载于:https://my.oschina.net/xd03122049/blog/1613990

@startuml PLPPSystem Class Diagram ' 主题和风格设置 !theme plain skinparam dpi 300 skinparam classAttributeIconSize 0 skinparam classFontStyle bold skinparam classFontSize 12 skinparam packageFontStyle bold ' 包声明 package "com.plppsystem.model" { ' 用户相关 class User { -Long id -String username -String password -String email -String fullName -LocalDateTime createdAt -LocalDateTime updatedAt -Boolean enabled +Set<Role> roles +StudentProfile studentProfile } class Role { -Long id -String name -String description } class StudentProfile { -Long id -User user -LearningStyle learningStyle -LocalDateTime styleUpdatedAt -Integer logicalAbility -Integer verbalAbility -Integer abstractAbility -Integer memoryAbility -Integer concentrationAbility -LocalDateTime abilityUpdatedAt -Set<InterestTag> interestTags -LocalDateTime interestsUpdatedAt -String learningGoal -String major -String learningPreference -LocalDateTime createdAt -LocalDateTime updatedAt +List<AbilityAssessment> abilityAssessments +List<InterestTag> interests } enum LearningStyle { VISUAL AUDITORY READ_WRITE KINESTHETIC } ' 学习资源相关 class LearningResource { -Long id -String title -String description -String resourceType -String difficultyLevel -Integer estimatedTime -String url -String filePath -String author -User createdBy -LocalDateTime createdAt -LocalDateTime updatedAt +Set<ResourceTag> tags +Subject subject +Set<LearningActivity> activities } class ResourceTag { -Long id -String name -String category -String description +Set<LearningResource> resources } class Subject { -Long id -String name -String code -String description -String category -Integer level +Set<LearningResource> resources } class InterestTag { -Long id -String name -String category -String description +Set<StudentProfile> students } ' 学习路径相关 class LearningPath { -Long id -String title -String description -String objective -String difficultyLevel -Integer estimatedDuration -User createdFor -User createdBy -LocalDateTime createdAt -LocalDateTime updatedAt -Boolean isPublished +List<LearningActivity> activities } class LearningActivity { -Long id -LearningPath learningPath -String title -String description -String activityType -LearningResource resource -Integer sequenceOrder -Integer estimatedTime -Boolean isRequired -LocalDateTime createdAt -LocalDateTime updatedAt +Set<LearningProgress> progressRecords } class LearningProgress { -Long id -User user -LearningActivity activity -String status -Integer completionPercentage -Integer timeSpent -LocalDateTime startTime -LocalDateTime lastAccessTime -LocalDateTime completedTime -String notes } ' 评估相关 class AbilityAssessment { -Long id -User user -Integer logicalScore -Integer verbalScore -Integer abstractScore -Integer memoryScore -Integer concentrationScore -String assessmentType -LocalDateTime assessmentDate -String notes } class LearningStyleAssessment { -Long id -User user -Integer visualScore -Integer auditoryScore -Integer readWriteScore -Integer kinestheticScore -LearningStyle dominantStyle -LocalDateTime assessmentDate -String notes } class LearningAssessment { -Long id -User user -String assessmentType -String assessmentTitle -String description -Integer score -String feedback -LocalDateTime assessmentDate -String notes } ' 学习行为和报告相关 class LearningBehavior { -Long id -User user -String behaviorType -String description -Integer duration -LocalDateTime recordTime -String resourceType -String resourceId -String notes } class LearningReport { -Long id -User user -String reportType -String reportTitle -String content -LocalDateTime generatedTime -LocalDateTime startPeriod -LocalDateTime endPeriod -String notes } ' 推荐相关 class RecommendationRecord { -Long id -User user -String recommendationType -String itemType -Long itemId -String itemTitle -String reason -Double score -Boolean isAccepted -LocalDateTime recommendedAt -LocalDateTime respondedAt -String notes } class RecommendationAlgorithmConfig { -Long id -String algorithmName -String algorithmType -Boolean isActive -Double weightLearningStyle -Double weightAbility -Double weightInterest -Double weightPriorPerformance -Double weightPopularity -String configData -LocalDateTime createdAt -LocalDateTime updatedAt } class CustomUserDetails { -User user +Collection<GrantedAuthority> authorities +String password +String username +boolean accountNonExpired +boolean accountNonLocked +boolean credentialsNonExpired +boolean enabled } } package "com.plppsystem.controller" { class UserController class AuthController class StudentProfileController class LearningResourceController class ResourceTagController class InterestTagController class LearningPathController class AssessmentController class RecommendationController class LearningReportController class LearningAnalyticsController class CrossDisciplineController } package "com.plppsystem.service" { interface UserService interface StudentProfileService interface LearningResourceService interface ResourceTagService interface InterestTagService interface LearningPathService interface AILearningPathService interface AssessmentService interface RecommendationService interface CrossDisciplineRecommendationService interface LearningReportService interface LearningAnalyticsService class UserDetailsServiceImpl } package "com.plppsystem.repository" { interface UserRepository interface RoleRepository interface StudentProfileRepository interface LearningResourceRepository interface ResourceTagRepository interface InterestTagRepository interface SubjectRepository interface LearningPathRepository interface LearningActivityRepository interface LearningProgressRepository interface AbilityAssessmentRepository interface LearningStyleAssessmentRepository interface LearningAssessmentRepository interface LearningBehaviorRepository interface LearningReportRepository interface RecommendationRecordRepository } package "com.plppsystem.algorithm" { interface RecommendationAlgorithm class ContentBasedAlgorithm class CollaborativeFilteringAlgorithm class HybridRecommendationAlgorithm class CrossDisciplineRecommendationAlgorithm class PathGenerateAlgorithm class PathAdjustmentAlgorithm } ' 关系定义 ' 用户角色、学生档案关系 User "1" -- "n" Role : has > User "1" -- "1" StudentProfile : has > StudentProfile -- LearningStyle : has > ' 学习资源关系 LearningResource "n" -- "n" ResourceTag : tagged with > LearningResource "n" -- "1" Subject : belongs to > LearningResource "1" -- "n" LearningActivity : used in > ' 学习路径关系 LearningPath "1" -- "n" LearningActivity : contains > LearningActivity "1" -- "n" LearningProgress : tracks > ' 评估关系 User "1" -- "n" AbilityAssessment : has > User "1" -- "n" LearningStyleAssessment : has > User "1" -- "n" LearningAssessment : has > ' 学习行为和报告关系 User "1" -- "n" LearningBehavior : has > User "1" -- "n" LearningReport : has > User "1" -- "n" RecommendationRecord : receives > ' 兴趣标签关系 StudentProfile "n" -- "n" InterestTag : interested in > ' 算法实现关系 RecommendationAlgorithm <|.. ContentBasedAlgorithm RecommendationAlgorithm <|.. CollaborativeFilteringAlgorithm RecommendationAlgorithm <|.. HybridRecommendationAlgorithm RecommendationAlgorithm <|.. CrossDisciplineRecommendationAlgorithm RecommendationAlgorithm <|.. PathGenerateAlgorithm RecommendationAlgorithm <|.. PathAdjustmentAlgorithm ' MVC架构关系 UserController --> UserService : uses > AuthController --> UserService : uses > StudentProfileController --> StudentProfileService : uses > LearningResourceController --> LearningResourceService : uses > ResourceTagController --> ResourceTagService : uses > InterestTagController --> InterestTagService : uses > LearningPathController --> LearningPathService : uses > LearningPathController --> AILearningPathService : uses > AssessmentController --> AssessmentService : uses > RecommendationController --> RecommendationService : uses > CrossDisciplineController --> CrossDisciplineRecommendationService : uses > LearningReportController --> LearningReportService : uses > LearningAnalyticsController --> LearningAnalyticsService : uses > ' 服务层数据访问层关系 UserService --> UserRepository : uses > StudentProfileService --> StudentProfileRepository : uses > LearningResourceService --> LearningResourceRepository : uses > ResourceTagService --> ResourceTagRepository : uses > InterestTagService --> InterestTagRepository : uses > LearningPathService --> LearningPathRepository : uses > LearningPathService --> LearningActivityRepository : uses > AssessmentService --> AbilityAssessmentRepository : uses > AssessmentService --> LearningStyleAssessmentRepository : uses > RecommendationService --> RecommendationRecordRepository : uses > LearningReportService --> LearningReportRepository : uses > LearningAnalyticsService --> LearningBehaviorRepository : uses > ' 算法服务层关系 RecommendationService --> RecommendationAlgorithm : uses > AILearningPathService --> PathGenerateAlgorithm : uses > AILearningPathService --> PathAdjustmentAlgorithm : uses > CrossDisciplineRecommendationService --> CrossDisciplineRecommendationAlgorithm : uses > ' 安全相关 UserDetailsServiceImpl --> UserRepository : uses > CustomUserDetails --> User : wraps > @enduml 我想通过drawIoAi工具绘制系统类图
最新发布
06-02
<think>好的,我需要帮助用户通过draw.io的AI工具绘制系统类图。首先,我需要理解用户提供的UML代码的结构和内容。用户已经给出了详细的类图,包括各个包、类、属性和关系。接下来,用户希望使用draw.io的AI工具来生成这个类图,可能需要指导如何操作。 首先,我应该回顾draw.io的AI功能。draw.io的AI工具可能允许用户输入文本描述,自动生成图表。但具体步骤可能包括:打开draw.io,启用AI功能,输入描述或代码,调整生成的图表。然而,用户提供的UML代码是PlantUML格式,而draw.io是否直接支持导入PlantUML可能需要确认。如果支持,用户可以直接导入;如果不支持,可能需要转换步骤。接下来,我应该考虑用户可能的实际操作步骤。如果draw.io支持PlantUML导入,那么用户只需将代码粘贴到draw.io的相应界面即可。否则,可能需要先将PlantUML转换为draw.io支持的格式,或者手动调整。但根据用户的问题,重点是利用AI工具生成,所以可能需要使用自然语言描述,让AI理解并生成类图。但根据用户提供的UML代码,可能更有效的方法是直接使用PlantUML工具生成图表,然后导出到draw.io进行编辑。或者,draw.io本身可能支持PlantUML的集成。我需要确认这一点,并提供步骤指导。可能的步骤包括: 1.将PlantUML代码保存为文本文件。2.使用在线PlantUML渲染工具生成图表。 3.导出为SVG或XML格式,再导入到draw.io中。4.在draw.io中进一步调整布局和样式。 另外,用户提到使用draw.io的AI工具,可能需要通过文本描述让AI生成类图。在这种情况下,用户需要将UML结构转换为自然语言描述,输入到AI中。例如,描述各个类、属性、关系等。但这样可能效率较低,不如直接使用PlantUML转换工具。因此,正确的解决方案可能是指导用户如何将现有的PlantUML代码转换为draw.io可用的格式,或者利用draw.io的PlantUML支持直接生成图表。如果draw.io不支持PlantUML,可能需要使用中间工具转换,再导入。此外,用户可能需要调整生成的图表样式,如颜色、布局、字体等,以符合需求。因此,步骤中应包括如何调整这些元素。 总结解决方案步骤: 1.确认draw.io是否支持PlantUML导入。如果支持,直接粘贴代码生成图表。2.如果不支持,使用在线PlantUML渲染工具生成图表,导出为图片或SVG,再导入到draw.io。 3.使用draw.io的AI功能,可能需要将UML结构转换为自然语言描述,输入AI生成类图,但可能不够准确。4.手动调整生成的图表,确保符合原始设计。然后,我需要将这些步骤以清晰的方式呈现给用户,并解释每个步骤的操作方法。同时,提醒用户注意可能的问题,如类图元素的对齐、关系的正确连接等。最后,根据用户的问题,提出相关问题,例如如何优化类图结构、如何处理复杂关系、其他UML工具的比较等。</think>针对使用draw.io AI工具绘制系统类图的需求,以下是详细解决方案: 1. PlantUML原生支持方案(推荐): ```plantuml @startuml ' 此处直接使用用户提供的原始PlantUML代码 @enduml ``` draw.io原生支持PlantUML导入,操作步骤: - 打开draw.io编辑器 - 选择"Arrange > Insert > Advanced > PlantUML" - 粘贴原始PlantUML代码 - 点击"Insert"自动生成类图 2. AI生成辅助方案(需要手动修正): ```markdown 向draw.io AI输入以下提示词: "创建包含以下元素的智能学习系统类图: 包结构: - com.plppsystem.model(核心模型) ▸ User用户模型:包含id、username、roles关联等 ▸ StudentProfile学生档案:关联学习风格、能力评估 ▸ LearningResource学习资源:包含资源类型、难度等级等 ▸ LearningPath学习路径:包含活动序列和进度跟踪 - com.plppsystem.controller(控制器层) - com.plppsystem.service(服务层) - 其他包结构... 重要关系: - UserStudentProfile是1对1关系 - LearningPath包含多个LearningActivity - 推荐算法实现关系..." ``` 3. 手动调整建议代码: ```javascript // 调整后的XML格式(draw.io原生格式) <mxGraphModel> <root> <mxCell id="0"/> <mxCell id="1" parent="0"/> <mxCell id="2" value="User" style="swimlane;fontStyle=1" vertex="1" parent="1"> <mxGeometry x="120" y="60" width="120" height="240" as="geometry"/> </mxCell> <mxCell id="3" value="StudentProfile" style="swimlane;fontStyle=0" vertex="1" parent="1"> <mxGeometry x="320" y="60" width="160" height="180" as="geometry"/> </mxCell> <mxCell id="4" value="" edge="1" source="2" target="3" parent="1"> <mxGeometry relative="1" as="geometry"/> </mxCell> </root> </mxGraphModel> ``` 关键调整点: 1. 使用分层布局(右上角Layout选项卡) 2. 设置统一配色(Format面板) 3. 调整关联线类型: - 继承关系:空心箭头 - 组合关系:实心菱形箭头 - 依赖关系:虚线箭头
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值